How many ways we can set a Thread name ?
- Thread foo = new Thread(“Foo”);
- Thread t = new Thread(); t.setName(“Foo”);
- Thread.currentThread().setName(“Thread-11”);
Why to name a Thread ?
- By default jvm names threads as Thread-0, Thread-1, Thread-2 and so on which are not very helpful in identifying which thread is doing what job.
- Naming a Thread helps us identify what is suppose to do just by looking the name of the thread in logs. This making life easy for debugging
When can be name a Thread?
- At the time of Thread creation.
- During execution of Task i.e while Thread is running.
Thread.currentThread() method will fetch the currently executing Thread object and then you can set or get the name of the thread using setName(<new name>), getName() method respectively. Sample below.
import java.util.stream.IntStream; public class ThreadNameDemo { public static void main(String[] args) { new Thread(new TempThread()).start(); IntStream.rangeClosed(1,10).forEach(x -> System.out.println(Thread.currentThread().getName()+" "+x)); } } class TempThread implements Runnable{ @Override public void run() { Thread.currentThread().setName("Child thread"); IntStream.rangeClosed(1,10).forEach(x -> System.out.println(Thread.currentThread().getName()+" "+x)); } }