Get current thread in Java


A thread can be created by implementing the Runnable interface and overriding the run() method.

The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread. This method requires no parameters.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Demo extends Thread {
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + Thread.currentThread().getName());
      }
   }
   public static void main(String[] args) {
      Demo t1 = new Demo();
      t1.setName("Main Thread");
      t1.start();
      Thread t2 = currentThread();
      t2.setName("Current Thread");
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + t1.currentThread().getName());
      }
   }
}

Output

The output of the above program is as follows −

The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements