Fetching the name of the current thread in Java



The name of the current thread can be obtained using the below code −

Example

 Live Demo

import java.io.*;
class name_a_thread extends Thread {
   @Override
   public void run() {
      System.out.println("Fetching the name of the current thread-");
      System.out.println(Thread.currentThread().getName());
   }
}
public class Demo {
   public static void main (String[] args) {
      name_a_thread thr_1 = new name_a_thread();
      name_a_thread thr_2 = new name_a_thread();
      thr_1.start();
      thr_2.start();
   }
}

Output

Fetching the name of the current thread-
Thread-0
Fetching the name of the current thread-
Thread-1

A class named ‘name_a_thread’ extends to the parent class Thread. It overrides the ‘run’ method, and relevant message is displayed on the console when this function is called. A class named Demo contains the main function, where two instances of the class are created. Both these instances are called using the ‘start’ function.


Advertisements