Naming Threads in Java: Manage Thread Names with Ease

Learn how to name and manage threads in Java using the Thread class’s setName() and getName() methods. Proper thread naming enhances debugging and monitoring, making multithreaded applications easier to track and manage.



Naming Thread

The Thread class in Java allows us to manipulate thread names using methods like setName() and getName().

Syntax


public String getName()
public void setName(String name)
        

Example: Naming a Thread using setName()


class MyThread extends Thread {
public void run() {
    System.out.println("running...");
}
}

public class TestThread {
public static void main(String[] args) {
    MyThread t1 = new MyThread();
    MyThread t2 = new MyThread();

    System.out.println("Name of t1: " + t1.getName());
    System.out.println("Name of t2: " + t2.getName());

    t1.start();
    t2.start();

    t1.setName("Sonoo Jaiswal");
    System.out.println("After changing name of t1: " + t1.getName());
}
}
        
Output

Name of t1: Thread-0
Name of t2: Thread-1
After changing name of t1: Sonoo Jaiswal
running...
running...
        

Example: Naming a Thread without using setName()


class MyThread extends Thread {
public MyThread(String threadName) {
    super(threadName);
}

public void run() {
    System.out.println("The thread is executing....");
}
}

public class TestThread {
public static void main(String[] args) {
    MyThread th1 = new MyThread("Java is Awesome");
    MyThread th2 = new MyThread("Java is Great");

    System.out.println("Thread - 1: " + th1.getName());
    System.out.println("Thread - 2: " + th2.getName());

    th1.start();
    th2.start();
}
}
        
Output

Thread - 1: Java is Awesome
Thread - 2: Java is Great
The thread is executing....
The thread is executing....
        

Current Thread

The currentThread() method in Java returns a reference to the currently executing thread.

Example


class MyThread extends Thread {
public void run() {
    System.out.println(Thread.currentThread().getName());
}
}

public class TestThread {
public static void main(String[] args) {
    MyThread t1 = new MyThread();
    MyThread t2 = new MyThread();

    t1.start();
    t2.start();
}
}
        
Output

Thread-0
Thread-1