Java Thread setName() Example


 

Java Thread setName() Example

In this section we are going to describe setName() method with example in java thread.

In this section we are going to describe setName() method with example in java thread.

Java Thread setName() Example

In this section we are going to describe setName() method with example in java thread.

Thread setName() :  Suppose,  you want to change name of your thread so for that java thread provides method setName(). You can add some new desired name to your thread. To display name of thread you can call getName() method.

public final void setName(String name) : this method changes the name of given thread which is equal to the argument. It provides new name to thread. It throws SecurityException if thread is not modify.

public final String getName() : This method returns name of the thread.

Example :

public class ThreadSetName implements Runnable {

	Thread thread;

	public ThreadSetName() {
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		/* Call getName() of the thread */
		System.out.println("Current Thread name : " + thread.getName());

		/* Setting new name to the thread */
		thread.setName("Roseindia" + thread.getName());

		/* Call getName() of the thread */
		System.out.println("After setting new name of thread : "
				+ thread.getName());
	}

	public static void main(String[] args) {
		new ThreadSetName();
	}
}

Output :

Current Thread name : Thread-0
After setting new name of thread : RoseindiaThread-0

Ads