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