Set and Get the Name of Thread in Java

In this article, we will learn to set and get thread names in Java with simple examples using the built-in methods setName() and getName()  in the Thread class.

1. Getting Thread Name

By default, the Java compiler sets a default name of each thread while creating, and we can get the thread name by using the Thread.currentThread().getName() method.

In the following example, we created a Thread by implementing the Runnable interface and its run() method. This code will print the default name of the thread to the console.

Thread thread = new Thread(() -> {
        System.out.println(Thread.currentThread().getName());
});
thread.start();   //Prints Thread-0

If we create more threads then the number part in the default name will increment with the number of threads i.e. Thread-1, Thread-2, Thread-3... etc.

Similarly, default names are generated for threads running in the ExecutorService in the pattern of pool-1-thread-1.

ExecutorService executorService = Executors.newFixedThreadPool(3);

executorService.submit(() -> {
    System.out.println(Thread.currentThread().getName());   //Prints pool-1-thread-1
});

If we run 3 tasks in this executor then the thread names will be pool-1-thread-1, pool-1-thread-2, pool-1-thread-3. Check out the following example to better understand the naming pattern.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
  public static void main(String[] args) {
    ExecutorService executorService = null;
    try {
      executorService = Executors.newFixedThreadPool(3);   //pool-1

      executorService.submit(() -> {
        System.out.println(Thread.currentThread().getName());  //thread-1
      });

      executorService.submit(() -> {
        System.out.println(Thread.currentThread().getName());  //thread-2
      });

      executorService = Executors.newFixedThreadPool(3);   //pool-2

      executorService.submit(() -> {
        System.out.println(Thread.currentThread().getName());  //thread-1
      });
    } finally {
      executorService.shutdown();
    }
  }
}

The program output is:

pool-1-thread-1
pool-1-thread-2

pool-2-thread-1

2. Setting Name to Thread

We can set a custom name of the thread in two ways:

  • Thread class constructor
  • The Thread.setName() method

2.1. Using Thread Constructor

We can use one of the following constructors that accept the thread name as a parameter.

Thread(String name);
Thread(Runnable task, String name);
Thread(ThreadGroup group, String name);
Thread(ThreadGroup group, Runnable task, String name);

Let us see an example of using a constructor to set the name of a thread.

Thread thread = new Thread(() -> {
        System.out.println("Thread name is : " + Thread.currentThread().getName());  //Prints "Thread name is : Demo-Thread"
}, "Demo-Thread");

thread.start();

2.2. Using Thread.setName()

The setName() method takes a single string type argument and does not return anything. This method is helpful if we have not set the thread name during thread creation or threads are created using the lambda style syntax.

Thread thread= new Thread(() -> {
    System.out.println(Thread.currentThread().getName());  //Prints 'Custom-Thread'
});
oddThread.setName("Custom-Thread");

Similarly, we can use this method with ExecutorSerivce as well.

executorService.submit(() -> {
    Thread.currentThread().setName("Executor-Thread");

    System.out.println(Thread.currentThread().getName()); //Prints 'Executor-Thread'
});

3. Conclusion

This tutorial taught us different ways to set a new custom name for a thread. We used the thread class constructor and setName() method of the same class. Similarly, we used the getName() to get the thread name and understood the default names of threads given by JVM.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode