Getting and setting name of thread

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

Leave a Comment