Naming a thread in java

Here is the table content of the article will we will cover this topic.
1. Naming a thread in java
2. Importance of Naming a thread in java
3. Example of java thread setName() and getName()

Naming a thread in java

Naming a thread in java

In a java program, each thread has a name that is automatically provided by JVM. We can also set the Naming a thread in java by calling the setName() method. The name of thread can either be given by JVM while creating the thread or it can be given by programmer explicitly. By default, each thread has a name i.e. thread-0, thread-1, and so on.

Importance of Naming a thread in java

In a Multi-threading environment, multiple threads are working at the same time. Sometimes multiple threads execute the same code or same lines of code and we want to know which thread is executing the line of code. So, we can check this to get the name of the thread that provides ease for the programmer. 

We can set and get the name of the thread. Thread class provides two methods for name:

1. public final String getName()

2. public final synchronized void setName(String name)

1. public final String getName(): This method returns the name of the thread. It is a public and final method. Its return type is String.

2. public final synchronized void setName(String name): This method is used to set the name of the thread. It is a public, final, and synchronized method. Its return type is void it means it doesn’t return anything.
name: This method takes only one parameter of String type. A programmer can assign a new name to thread.

Example of java thread setName() and getName()

Let’s say we have three threads thread1, thread2, and thread3. If all the three threads are in RUNNABLE state and printing the counting of number. Here we want to know which thread is printing the counting of number at a time. So, we can use the setName() method to set the name and getName() method to get the name of the thread.

public class ExampleOfNaming extends Thread 
{		
   public void run()
   {  
	for(int i = 1; i <= 5; i++)
	{  
           System.out.println(Thread.currentThread().getName() + " is running 
           and value of i = "+i);  
	}  
   }  
   public static void main(String args[])
   {  
	 ExampleOfJoinMethod thread1 = new ExampleOfJoinMethod();  
	 thread1.setName("Thread1");
	 ExampleOfJoinMethod thread2 = new ExampleOfJoinMethod();
	 thread2.setName("Thread2");
		 
	 thread1.start();  
				
	 thread2.start();  
   }  
}

Output:
Thread1 is running and value of i = 1
Thread2 is running and value of i = 1
Thread1 is running and value of i = 2
Thread2 is running and value of i = 2
Thread1 is running and value of i = 3
Thread2 is running and value of i = 3
Thread2 is running and value of i = 4
Thread1 is running and value of i = 4
Thread2 is running and value of i = 5
Thread1 is running and value of i = 5

Leave a Comment