Java Thread currentThread() Method



Description

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

Declaration

Following is the declaration for java.lang.Thread.currentThread() method

public static Thread currentThread()

Parameters

NA

Return Value

This method returns the currently executing thread.

Exception

NA

Example: Getting Current Thread in Multi-threaded program

The following example shows the usage of Java Thread currentThread() method. In this example, we've created a thread class ThreadDemo by implementing Runnable Interface. In ThreadDemo constructor currently active thread is retrieved using currentThread method, a new thread is created and both are printed.

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   ThreadDemo() {
      // main thread
      Thread currThread = Thread.currentThread();
      
      // thread created
      Thread t = new Thread(this, "Admin Thread");
   
      System.out.println("current thread = " + currThread);
      System.out.println("thread created = " + t);
      
      // this will call run() function
      t.start();
   }

   public void run() {
      System.out.println("This is run() method");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

current thread = Thread[main,5,main]
thread created = Thread[Admin Thread,5,main]
This is run() method

Example: Getting Current Thread in Single-threaded program

The following example shows the usage of Java Thread currentThread() method. In this example, we've created a thread class ThreadDemo. In main method, currently active thread is retrieved using currentThread method, and is printed.

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      System.out.println("current thread = " + currThread);
   }
}   

Output

Let us compile and run the above program, this will produce the following result −

current thread = Thread[#1,main,5,main]
java_lang_thread.htm
Advertisements