/**
* 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()
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!