«Back to Home

Core Java

Topics

Naming Thread And Current Thread In Java

Naming Thread

In Java, Thread class provides methods to change or set and get the name of a thread.
 
By default, every thread has a name i.e. thread-0, thread-1 and so on.
 
We can change the name of the thread with the usage of setName() method.
 
Syntax

public String getName()

This method is used to return the name of a thread.
 
public void setName(String name)

This method is used to change the name of a thread.
 
Let’s see an example of naming a thread, given below.
 
Code
  1. public class JoinMethod extends Thread {  
  2.     public void run() {  
  3.         System.out.println("threads running fast...");  
  4.     }  
  5.     public static void main(String args[]) {  
  6.         JoinMethod t1 = new JoinMethod();  
  7.         JoinMethod t2 = new JoinMethod();  
  8.         System.out.println("Name of thread 1:" + t1.getName());  
  9.         System.out.println("Name of thread 2:" + t2.getName());  
  10.         System.out.println("id of thread 1:" + t1.getId());  
  11.         t1.start();  
  12.         t2.start();  
  13.         t1.setName("Strong Thread");  
  14.         System.out.println("After changing name of thread 1:" + t1.getName());  
  15.     }  
  16. }  
19

Output

20

In the example, mentioned above, we can see that with the help of the methods, we can get or set the name of the thread and also change it.
 
CurrentThread() method

The CurrentThread() method is used to return a reference to the currently executing thread object.
 
Syntax

Public static Thread currentThread()
 
Let’s see a simple example, given below.
 
Code
  1. public class CurrentThreadMethod extends Thread {  
  2.     public void run() {  
  3.         System.out.println(Thread.currentThread().getName());  
  4.     }  
  5.   
  6.     public static void main(String args[]) {  
  7.         CurrentThreadMethod t1 = new CurrentThreadMethod();  
  8.         CurrentThreadMethod t2 = new CurrentThreadMethod();  
  9.         t1.start();  
  10.         t2.start();  
  11.     }  
  12. }  
21

Output

22

In the example, mentioned above, we can see that with the usage of currentThread() method, we can easily get the name of the current thread, which is currently running.
 
Summary

Thus, we learnt, the methods to set and get the name of a thread, currentThread() method and also learnt, how to use these methods in Java.