Naming a thread in java

1. public final void setName(String name)

Changes the name of the thread.

name – new name for this thread.

2. public final String getName()

Returns this thread’s name.

Example:

ThreadExample.java

/**
 * This program is used to show the thread naming example.
 * @author w3spoint
 */
class Test extends Thread{
	public void run(){
		//Thread.currentThread()returns the current thread.
		System.out.println("Id of running thread: " + 
				Thread.currentThread().getId() + 
				" Name of running thread: " + 
				Thread.currentThread().getName());
	}
}
 
public class ThreadExample {
	public static void main(String args[]){
		//creating thread.
		Test thrd1 = new Test();
		Test thrd2 = new Test();
 
		//set thread name.
		thrd1.setName("My Thread1");
		thrd2.setName("My Thread2");
 
		//start the thread.
		thrd1.start();
		thrd2.start();
	}
}

Output:

Id of running thread: 9 Name of running thread: My Thread2
Id of running thread: 8 Name of running thread: My Thread1

Download this example.
 
Next Topic: Joining a thread in java with example.
Previous Topic: Thread priority in java with example.

Content Protection by DMCA.com
Please Share