Java - Thread Current Thread

Which Thread Is Executing?

Thread class currentThread() method returns the reference of the current Thread object.

Consider the following statement:

Thread t = Thread.currentThread();

The statement will assign the reference of the thread object that executes the above statement to the variable t.

A statement in Java can be executed by different threads at different points.

t may be assigned the reference of a different Thread object.

The following code demonstrates the use of the currentThread() method.

Two different threads call the Thread.currentThread() method inside the run() method.

The method returns the reference of the thread executing the call.

The program prints the name of the thread that is executing.

Demo

public class Main extends Thread {
  public Main(String name) {
    super(name);// w  ww. j a  v a 2  s . c  o m
  }

  @Override
  public void run() {
    Thread t = Thread.currentThread();
    String threadName = t.getName();
    System.out.println("Inside run() method: " + threadName);
  }

  public static void main(String[] args) {
    Main ct1 = new Main("First Thread");
    Main ct2 = new Main("Second Thread");
    ct1.start();
    ct2.start();

    // Let's see which thread is executing the following statement
    Thread t = Thread.currentThread();
    String threadName = t.getName();
    System.out.println("Inside main() method: " + threadName);
  }
}

Result