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

SetThreadNameExp.java
package org.websparrow.thread.methods;

public class SetThreadNameExp extends Thread {
	@Override
	public void run() {
		Thread thread = new Thread();
		thread.checkAccess();
		System.out.println("Before setting thread name is : " + thread.getName());
		// setName() sets the name of Thread
		thread.setName("WebSparrow.org");
		// 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();
		threadName.start();
	}
}

Output:

Before setting thread name is : Thread-1
After setting thread name is : WebSparrow.org

References

Class Thread


Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.