Set Thread name in Java

Description

The following code shows how to set Thread name.

Example


/*  w w w  .ja va2 s  .c o  m*/
public class Main {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();

    System.out.println("Current thread: " + t);

    t.setName("My Thread");
    System.out.println("After name change: " + t);

    try {
      for (int n = 5; n > 0; n--) {
        System.out.println(n);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted");
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Thread »




Data Structure
Semaphore
Thread