Naming a thread in Java

Java provides methods to change the name of the thread. These methods are defined in the ‘java.lang.Thread’ class. The name of the thread can be set directly by passing the name as an argument to the function. It has been demonstrated below −


 Live Demo

class name_a_thread extends Thread {
   name_a_thread(String name) {
   public void run() {
      System.out.println("Thread is currently running ");
public class Demo {
   public static void main (String[] args) {
      name_a_thread thr_1 = new name_a_thread("Joe");
      name_a_thread thr_2 = new name_a_thread("Billy");
      System.out.println("Name of thread 1 is : " + thr_1.getName());
      System.out.println("Name of thread 2 is : " + thr_2.getName());


Name of thread 1 is : Joe
Name of thread 2 is : Billy
Thread is currently running
Thread is currently running


A class named ‘name_a_thread’ extends to the parent class Thread. It defines a constructor that takes parameter as a string, and it is called using the ‘super’ function. The function ‘run’ is overridden, and relevant message is displayed on the console. A class named Demo contains the main function, where two instances of the ‘name_a_thread’ class are created, and two strings are passed as parameters respectively. The names of the threads are displayed on the console, with the help of the ‘getName’ function. Now, the two threads ar begun with the help of the ‘start’ function.