Thread Name

In this chapter you will learn:

  1. Get and set Thread Name
  2. How to set thread name

Thread Name

You can set the name of a thread by using setName(). You can obtain the name of a thread by calling getName().

These methods are members of the Thread class and are declared like this:

final void setName(String threadName) 
final String getName( )

Here, threadName specifies the name of the thread.

Set thread name

The following code sets name to threads.

public class Main {
  public static void main(String[] args) {
    Runnable r = new Runnable() {
      @Override/*from  j  av a2 s.  c  o  m*/
      public void run() {
        String name = Thread.currentThread().getName();
        int count = 0;
        while (count<Integer.MAX_VALUE) {
          System.out.println(name + ": " + count++);
          try {
            Thread.sleep(100);
          } catch (InterruptedException ie) {
          }
        }
      }
    };
    Thread thdA = new Thread(r);
    thdA.setName("A");
    Thread thdB = new Thread(r);
    thdB.setName("B");
    thdA.start();
    thdB.start();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is the main Java thread
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor