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 :

    Example)
    drag_handle
     
    //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);
    	}
    }
    Output:
    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 :

    Example)
    drag_handle
     
    //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());
    	}
    }
    Output:
    NewName

Setting name of UserThread
drag_handle
//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();
}
}

Output:

My Name is :First Thread

Note

We can get the reference of current executing thread by using following method of Thread class.
public static Thread currentThread()

What next?

The next topic is Thread Priority

Share this page