Get current thread in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 07-Feb-2019 17:36:34
Advertisements