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());
    }
}

Top Hashtags:

Advertisements

Advertisements




Advertisements