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();
  final Thread thread2 = new WorkerThread();
  final Thread thread3 = new WorkerThread();
  final Thread thread4 = new WorkerThread();
  System.out.println("Thread main finished");

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


Free Spring Boot Tutorial - 5 Hours Full Course

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