How to get Current Thread Name and Modify




Thread class has a static method currentThread() which returns a reference to the currently executing thread object.

getName() method of Thread class returns the name of a thread.

Using setName() of Thread class , name of a thread can be changed.

e.g.

Thread currentThrd = Thread.currentThread();
String threadName = currentThrd.getName();

Syntax of currentThread() , getName() , setName() methods:

public static native Thread currentThread();
public final String getName();
public final synchronized void setName(String name);

The below demo program explains how to get Current thread object reference, name of thread and how to modify the name of the thread.

Demo Example : Current Thread Name

package com.masterjavatutorial;
public class Test {
	 
	public static void main(String[] args) {
          
		 Thread currentThread = Thread.currentThread(); 
		 String name = currentThread.getName(); 
		 System.out.println("Current Thread Name = "+ name);
		 
		 currentThread.setName("Main Thread-1");
		 
		 String changedName = currentThread.getName(); 
		 System.out.println("Current Thread Changed Name = "+ changedName);
	
	}

}

Output of the above program is as below:

Current Thread Name = main
Current Thread Changed Name = Main Thread-1