Java Naming Thread

Java Naming a thread :

We can get / set the name of a thread by using the getName() and setName() method.

The Thread class provides methods to change and get the name of a thread.

Syntax Usage
public String getName() Used to return the name of a thread.
public void setName(String name) Used to change the name of a thread.

Program Example : Naming a thread

package com.c4learn.thread;
public class ThreadName extends Thread {
 public void run() {
	 System.out.println("Thread Running...");
 }
 public static void main(String[] args) 
                      throws InterruptedException {
   ThreadName t1 = new ThreadName();
   ThreadName t2 = new ThreadName();
   ThreadName t3 = new ThreadName();
   t1.start();
   System.out.println("Thread T1 : " + t1.getName());
   t2.start();
   System.out.println("Thread T2 : " + t2.getName());
   t1.setName("Thread - c4learn");	
   System.out.println("Thread T1 : " + t1.getName());
 }
}

Output :

Thread Running...
Thread T1 : Thread-0
Thread T2 : Thread-1
Thread T1 : Thread - c4learn
Thread Running...

Name of Currently Running Thread :

If we need to get the name of currently running method then we use following syntax -

Thread.currentThread().getName()

currentThread() method returns a reference to the currently executing thread object.

getName() method return the name of the currently running thread.

package com.c4learn.thread;
public class ThreadNameExample extends Thread {
 public void run() {
     String threadName = Thread.currentThread().getName();
     System.out.println(threadName );
 }
 public static void main(String[] args) 
                      throws InterruptedException {
   ThreadNameExample t1 = new ThreadNameExample();
   ThreadNameExample t2 = new ThreadNameExample();
   t1.start();
   t2.start();
 }
}

output :

Thread-0
Thread-1