Set thread name

In this blog post, we will take a look at 2 different ways to set the name of a thread in Java with example programs.

Why set thread name
When you create a new thread, you can give it a name. Java allows us to set a human-readable name for a thread.
If you do not specify a name for a thread, the Java runtime will itself assign a name to it. Typical examples of automatically generated threads are main, Thread-0, Thread-1 etc. Example,

// create a thread
Thread t = new Thread(
             () -> System.out.println(Thread.currentThread().getName())
           );
// run it
t.start();

Above code snippet creates a thread which simply prints its name and starts the thread.
To get the name of a thread, its getName() method is used.
Output is

Thread -0

which is the default name generated by JVM.
If more threads are created, then the number after Thread is incremented accordingly.

Following are the reasons to set the name of a thread
1. For debugging and monitoring purposes, as it can help you identify which thread executed a particular code, when looking at a stack trace.
2. To give the thread a more descriptive name than the default names.
3. To make the thread’s name available to other parts of the code, using Thread.currentThread().getName() method.
Set thread name
There are two ways to set a thread’s name in Java:
1. Using setName() method on the Thread instance.
java.lang.Thread class has a setName() method

Thread t = new Thread();
t.setName("Logging");

2. Using thread constructor
java.lang.Thread class has multiple constructors which takes a string argument as shown below

public Thread(ThreadGroup group, String name)
public Thread(Runnable target, String name)
public Thread(ThreadGroup group, Runnable target, String name)
public Thread(ThreadGroup group, Runnable target, String name, long stackSize)
public Thread(ThreadGroup group, Runnable target, String name, long stackSize, boolean inheritThreadLocals)

This string becomes the name of the thread. Example,

Thread t = new Thread("Logging");

Set thread name example
Below example creates two different threads, sets their name using constructor and setName() method and prints their name.

// first thread
Thread t1 = new Thread("Logger");
t1.start();
System.out.println("Name of t1 is: "+t1.getName());

// second thread
Thread t2 = new Thread(() -> {
    for (int i = 0; i < 5; i++) {
      System.out.println(i);
    }
      });
t2.setName("Printer");
System.out.println("Name of t2 is: "+t2.getName());

Output is

Name of t1 is: Logger
Name of t2 is: Printer

Hope the article was useful.