Java - How to set custom thread name?


In order to set the custom name for a thread, you can make use of setName(String name) method,

Example:
/**
 * Java Code Example: code2care.org
 *
 * Setting Thread Name
 * Thread.currentThread().getName()
 *
 */
public class ThreadExample extends Thread {

    public static void main(String[] args) {

        //Thread using Anonymous class
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.currentThread().setName("MyThread1");
                System.out.println("Thread Name: " + Thread.currentThread().getName());
            }
        });

        //Thread using Lambda expression
        Thread thread2 = new Thread(() -> {
            Thread.currentThread().setName("MyThread2");
            System.out.println("Thread Name: " + Thread.currentThread().getName());
        });

        //Thread using class that extends Thread Class
        ThreadExample thread3 = new ThreadExample();

        //Thread using Anonymous class with custom Name
        Thread thread4 = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.currentThread().setName("MyThread4");
                System.out.println("Thread Name: " + Thread.currentThread().getName());
            }
        },"MyCustomThreadName"); //run() will override this name

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

        System.out.println("Thread Name: " + Thread.currentThread().getName());

    }

    @Override
    public void run() {
        Thread.currentThread().setName("MyThread3");
        System.out.println("Thread Name: " + Thread.currentThread().getName());
    }
}
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.