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?
currentThread() method returns a reference to the currently executing thread object.
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.
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.
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).
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With