Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Thread.currentThread() work?

Thread.currentThread() is a static method which provides reference to currently executing Thread (basically a reference to 'this' thread).

Accessing non-static members (especially this) inside a static method is not possible in Java, so currentThread() is a native method.

How does currentThread() method work behind the scenes?

like image 242
maximus335 Avatar asked Feb 15 '15 15:02

maximus335


People also ask

What does thread currentThread () do?

currentThread() method returns a reference to the currently executing thread object.

What is thread currentThread () getName ()?

currentThread() returns a reference to the thread that is currently executing. In the above example, I've used thread's getName() method to print the name of the current thread. Every thread has a name. you can create a thread with a custom name using Thread(String name) constructor.

How do you get the currently running thread?

In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.

What happens when thread start is called in Java?

start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).


1 Answers

(basically a reference to 'this' thread)

There are no this references involved here.

You are mixing up a thread as a native resource, meaning the thread of execution; and Thread, which is a Java class. Thread code does not run "within" the Thread instance, that instance is just your handle into Java's thread control. Much like a File instance is not a file.

So, Thread.currentThread() is a way for you to retrieve the instance of Thread in charge of the thread-of-execution inside which the method is called. How exactly Java does this is an implementation detail which should not be your concern unless you are exploring the details of a particular JVM implementation.

like image 124
Marko Topolnik Avatar answered Sep 17 '22 13:09

Marko Topolnik