• August 29, 2014
  • Core Java
  • Comments Off on Naming a thread in java

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 javawithease
 */
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 priority.
		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.

Related Topics:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.

 


Comments are closed.