Java Thread setName() Method Example

Java Thread Examples


This post describes the usage of the Java Thread setName() method with an example.

Java Thread setName() Method Overview

The java.lang.Thread class provides methods to change and get the name of a thread. By default, each thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName() method. The syntax of setName() and getName() methods are given below:
  • public String getName(): is used to return the name of a thread.
  • public void setName(String name): is used to change the name of a thread.
Thread class provides a static currentThread() - Returns a reference to the currently executing thread object.

Java Thread setName() Method Example

/**
 *  Thread naming example using Thread class.
 *  @author Ramesh fadatare
 **/

public class ThreadExample {
 
 public static void main(final String[] args) {
  
  System.out.println("Thread main started");

  final Thread thread1 = new WorkerThread();
  thread1.setName("WorkerThread1");
  
  final Thread thread2 = new WorkerThread();
  thread2.setName("WorkerThread2");
  
  final Thread thread3 = new WorkerThread();
  thread3.setName("WorkerThread3");
  
  final Thread thread4 = new WorkerThread();
  thread4.setName("WorkerThread4");
  
  thread1.start();
  thread2.start();
  thread3.start();
  thread4.start();
  
  System.out.println("Thread main finished");
 }
}

class WorkerThread extends Thread {
 
 @Override
 public void run() {
  System.out.println("Thread Name :: " + Thread.currentThread().getName());
 }
}
Output:
Thread main started
Thread Name :: WorkerThread1
Thread Name :: WorkerThread2
Thread Name :: WorkerThread3
Thread main finished
Thread Name :: WorkerThread4

Reference

Comments