Current Thread Method java Current Thread Method java multithreading multithreading

Current Thread Method java


The code that calls currentThread will be executing in one of the threads, not in all of them, so it can get that thread specifically.


Suppose you have list of instructions printed on a piece of paper. A person reads the instructions and performs them. The instructions are a program. The person is a thread. You could make many copies of the paper and pass them out to many people. If the instructions say something like, "slap yourself," yourself refers to whomever is reading that instruction from that paper. Likewise, Thread.currentThread() refers to the thread that is executing that call to currentThread().


When an instruction in your code is executed, it is executed within a specific thread. This is the thread returned by that method.

Obviously, if a specific method is executed by multiple threads, each execution might return a different value for Thread.currentThread().

You could try this short example to get a better idea of what is going on and in particular the fact that the 2 threads execute in parallel. You should see that t1 will run a few loop then t2 will do the same and back to t1 etc (you might need to increase the number of loops from 5 to a higher number depending on your machine):

public class TestThread {    public static void main(String[] args) {        Runnable r = new Runnable() {            @Override            public void run() {                for (int i = 0; i < 5; i++) {                    System.out.println(Thread.currentThread());                }            }        };        Thread t1 = new Thread(r, "t1");        Thread t2 = new Thread(r, "t2");        t1.start();        t2.start();    }}