Get Current Thread Name In Java

 Posted On  | Yashwant Chavan 

While executing the Java thread, Some time we need to retrieve the Thread name, because multiple threads are executing concurrently along with the Main thread. Let have a sample code which display the thread name.

Thread.currentThread().getName()

It is going to return the Current executing thread name. You can also set the name of thread otherwise it will use the default name.

package com.technicalkeeda.app;
public class ThreadTest {

    public static void main(String[] args) {
        RunnableExample runnableExample = new RunnableExample();
        Thread t1 = new Thread(runnableExample);
        Thread t2 = new Thread(runnableExample);
        Thread t3 = new Thread(runnableExample);
        t1.start();
        t2.start();

        t3.setName("Third Thread");
        t3.start();
    }

}
package com.technicalkeeda.app;

public class RunnableExample implements Runnable {

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

Output:)

Refer below Out put

My Name is :- Third Thread
My Name is :- Thread-1
My Name is :- Thread-0


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0307 seconds.