Getting and Setting Name

Every thread in java has some name. It may be provided by the programmer or default name generated by JVM.

We can get and set the name of the thread by using the following methods of java.lang.Thread Class.
For Setting name : public void setName()
For Getting Name : public String getName()


Getting the name of Thread

use getName() method of Thread class for getting the name of any thread.
Let us see the example :


//getting the name of main thread
class Example
{
	public static void main(String[] args) {
		//getting the reference of current running thread
		Thread t=Thread.currentThread();
		//now get call the getName() method of t
		String threadName=t.getName();
		//print the thread name
		System.out.println(threadName);
	}
}
main

Setting the name of Thread

use setName(String Name) method of Thread class for setting the name of any thread.
Let us see the example :


//setting  the name of main thread
class Example
{
	public static void main(String[] args) {
		//getting the reference of current running thread
		Thread t=Thread.currentThread();
		//now get call the setName() method on t
		t.setName("NewName");
		//print the thread name
		System.out.println(t.getName());
	}
}
NewName
Setting name of UserThread
//example of creating userthread and setting new name for the thread
class UserThread extends Thread
{
public void run()
{
 Thread ur=Thread.currentThread();
 System.out.println("My Name is :"+ur.getName());

}
public static void main(String[] args) {
	UserThread t=new UserThread();
	t.setName("First Thread ");
	t.start();
}
}
My Name is :First Thread