Wednesday, September 18, 2013

Thread Naming in Java

Thread class provides following methods using which You can set name to Thread and retrieve thread name.
  • public final void setName(String name) - Changes name of Thread equals to argument
  • public final String getName() - Return Thread name


You can use Thread.currentThread() to get reference of current running thread.
As mentioned below, You can see currentThread() is static method so You can call Thread.currentThread() without "new" and can use Thread.currentThread().getName() to get name of current running thread.

Thread.class
public static native Thread currentThread();

Thread Naming Java Program :
package com.anuj.threading;

/**
 * Thread Naming Example
 * @author Anuj
 *
 */
class ThreadNamingExample extends Thread{

 @Override
 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadNamingExample t1 = new ThreadNamingExample();
  ThreadNamingExample t2 = new ThreadNamingExample();

  System.out.println("t1 - "+ t1.getName());
  System.out.println("t2 - "+ t2.getName());
  
  t1.start();
  t2.start();
  
  t1.setName("Anuj");
  System.out.println("t1 - "+t1.getName());
 }
}

Output:
t1 - Thread-0
t2 - Thread-1
t1 - Anuj
Anuj - 1
Thread-1 - 1
Thread-1 - 2
Anuj - 2
Thread-1 - 3
Anuj - 3
Anuj - 4
Thread-1 - 4
Anuj - 5
Thread-1 - 5

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/