Share on Google+Share on Google+

Java Thread setName() Example

Advertisement
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

Advertisements

Posted on: October 22, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.