Skip to Content

Set Thread Name Example

  1. /*
  2.         Set Thread Name Example
  3.         This Java example shows how to set name of thread using setName method
  4.         of Thread class.
  5. */
  6.  
  7. public class SetThreadNameExample {
  8.  
  9.         public static void main(String[] args) {
  10.                
  11.                 //get currently running thread object
  12.                 Thread currentThread = Thread.currentThread();
  13.                 System.out.println(currentThread);
  14.                
  15.                 /*
  16.                  * To set name of thread, use
  17.                  * void setName(String threadName) method of
  18.                  * Thread class.
  19.                  */
  20.                
  21.                 currentThread.setName("Set Thread Name Example");
  22.                
  23.                 /*
  24.                  * To get the name of thread use,
  25.                  * String getName() method of Thread class.
  26.                  */
  27.                 System.out.println("Thread Name : "+ currentThread.getName());
  28.         }
  29. }
  30.  
  31. /*
  32. Output of the example would be
  33. Thread[main,5,main]
  34. Thread Name : Set Thread Name Example
  35. */