How to set and get Thread name in Java

This Java tutorial will explain how to set and get a thread name in Java. Thread class provides two methods for handling the thread name. Every thread has a name by default like thread-0, thread-1, and thread-2 and so on. But by using setName() method we can set the thread name according to our convenience and using getName() method we can see the thread name.

1- public void setName(String name)– Changes the name of thread to be equal to the argument name.

2- public String getName()– return the name of Thread.

Note: setName() method throws the SecurityException if the current thread cannot modify this thread.

Example of set and get Thread name
package org.websparrow.thread.methods;

public class SetThreadNameExp extends Thread {
	public void run() {
		Thread thread = new Thread();
		System.out.println("Before setting thread name is : " + thread.getName());
		// setName() sets the name of Thread
		// getName() return the name of Thread
		System.out.println("After setting thread name is : " + thread.getName());

	public static void main(String[] args) throws SecurityException {
		SetThreadNameExp threadName = new SetThreadNameExp();


Before setting thread name is : Thread-1
After setting thread name is :


Class Thread

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.