How to get Java Thread name Example [Program]


Program:
/**
 * Java Code Example: code2care.org
 *
 * Getting Thread Name
 * Thread.currentThread().getName()
 *
 * Custom Thread Name
 *
 */
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() {
                System.out.println("Thread Name: " + Thread.currentThread().getName());
            }
        });

        //Thread using Lambda expression
        Thread thread2 = new Thread(() -> 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() {
                System.out.println("Thread Name: " + Thread.currentThread().getName());
            }
        },"MyCustomThreadName");

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

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

    }

    @Override
    public void run() {
        System.out.println("Thread Name: " + Thread.currentThread().getName());
    }
}
Output:

Thread Name: Thread-1
Thread Name: Thread-2
Thread Name: main
Thread Name: MyCustomThreadName
Thread Name: Thread-0

To get the name of the current thread you can make use of Thread.currentThread().getName()


Top Hashtags:

Advertisements

Advertisements




Advertisements