setName() & getName() Methods

Change name of method

In java every thread has a default name in format of Thread-0 where 0 is replaced by sequence number of that thread. Java allows programmer to change name of thread for better understandability of their code.

Example

  class mythread implements Runnable
  {
   public void run()
    {
	  System.out.println("Execution....");
	}
  }
  class impl
 {
   public static void main(String arg[])
    {
	 mythread th=new mythread();
	 Thread t=new Thread(th);
	 
	 System.out.println("Before Change Thread Name:"+t.getName());
	 
	 // Changing Name
	 t.setName("Demo Thread");
	 System.out.println("After Chande Thread Name:"+t.getName());
	}
 }  
/* Output:
Before Change Thread Name:Thread-0
After Chande Thread Name:Demo Thread
*/ 
  


Name of Currently Running Thread

Currently running thread object's reference can be fetched using currentThread() method. This is static method of Thread class.

  Thread cur=Thread.currentThread();
  String name=cur.getName();
  

Above code will fetch reference of currently running object and second statement will fetch name of that thread.

  class mythread implements Runnable
  {
   public void run()
    {
	  Thread cur=Thread.currentThread();
	  System.out.println("Execution...."+cur.getName());
	}
  }
  class impl
 {
   public static void main(String arg[])
    {
	 mythread th=new mythread();
	 Thread t=new Thread(th);
	 t.start();
	 
	 Thread t1=new Thread(th);
	 t1.setName("Demo Thread");
	 t1.start();
	}
 } 
/* Output:
Execution....Thread-0
Execution....Demo Thread
*/