Home » Java programming language

How to get and set name of a thread in Java?



Learn: how to get and set name of a thread in Java? Define getName() and setName(String str) methods in java? How to replace name of a Thread in Java?
Submitted by Preeti Jain, on March 03, 2018

How to get and set name of a Thread in Java?

  • Every Thread in java has some unique name. It may be provided by the developer (user defined) or default name (if user not defined) generated by JVM (JVM defined).
  • We can get name of a Thread by using the method of Thread class: public final String getName();
  • We can set name of a Thread by using the method of Thread class: public final void setName(String name);

Example 1: Get name of a Thread

class GetName{
	public static void main(String[] args){
		String tn = Thread.currentThread().getName();
		System.out.println(tn);
	}
}

Output:

E:\javasource>java GetName
main

Here, Thread.currentThread().getName() - currentThread() is a static method of Thread class . By this we can get current executing Thread and getName() will give the name of a Thread.

Example 2: Set name of a Thread

class SetName{
	public static void main(String[] args){
		Thread.currentThread().setName("main is changed to parent");
		System.out.println(Thread.currentThread().getName());
	}
}

Output

E:\javasource>java SetName
main is changed to parent

Here, Thread.currentThread().setName("main is changed to parent") - Current thread is main thread so name of main is replaced with main is changed to parent by the method setName(String str)

Related thread posts...

  1. Explain life cycle of a thread in java.
  2. Thread properties in java.
  3. How to Create Java Threads (java examples to create threads)?
  4. Thread Synchronisation in Java with Example.
  5. Difference between Process and Thread in java.
  6. Differences between User Thread and Daemon Thread in Java.
  7. How to create daemon thread in java?
  8. What will happen if we don't override thread class run() method in java?
  9. How can we achieve Thread Safety in java?
  10. Thread Scheduler and Time Slicing in Java.
  11. Thread pool in java, how to create it?
  12. What is Multi Threading in Java?





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.