Java Thread Set Name Example

In this article, we will learn how to name a thread in a Java application.

getName() and setName(String name) 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.

Naming a Thread Example

In this example, we have used setName() and currentThread() methods. Let's create 4 threads and name these threads as:
  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");
Let's see a complete program to demonstrates how to name a thread.
/**
 *  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

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments