Naming a thread in Java

Java 8Server Side ProgrammingProgramming

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 −

Example

 Live Demo

import java.io.*;
class name_a_thread extends Thread {
   name_a_thread(String name) {
      super(name);
   }
   @Override
   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());
      thr_1.start();
      thr_2.start();
   }
}

Output

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

Explanation

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.

raja
Published on 14-Sep-2020 12:29:24
Advertisements