How to get Thread ID in Java with Example

ThreadId can be obtained from the Thread.currentThread()  method.

Read Also :   Multithreading Interview Questions in Java


What is thread ID in java?

According to Oracle docs , thread ID is the identifier of the thread.  The thread ID is a positive long number generated when the thread is created.
Note : thread ID  remains unique and unchanged during the lifetime of the thread. When a thread is terminated then its thread ID may be reused.

There are two ways to get thread ID in Java , one is by getting the reference of the current thread i.e Thread.currentThread() and the other is using Thread.get

currentThread() method in Java

currentThread() is a static method , returns a reference to the currently executing thread object.

After getting the reference of the current thread , we will call the getId() method on Thread class.


getId() method in Java


getId() will return the unique identifier of current thread which is a positive long value.



import java.lang.*;

public class ThreadIdExample   {
    
    public static void main(String[] args) { 
        WorkerThread workerthreadobject = new WorkerThread();

        //  below is the first constructor : setting name also

        Thread  t1 = new Thread(workerthreadobject);
        t1.setName("First Thread");
        t1.start();

        //  below is the second constructor : setting name as argument    

        Thread  t2 = new Thread(workerthreadobject , "Second Thread");
        t2.start();
      
       // below we will not set any name of the thread
  
       Thread  t3 = new Thread(workerthreadobject);
        t3.start();
// Getting the current thread object i.e Main thread
Thread currentThread = Thread.currentThread();
// Printing Main thread : name and id
System.out.println("Executing thread : " + currentThread.getName()) ;
 System.out.println("id of the thread is " + currentThread.getId());
 
 }
}




 class WorkerThread implements Runnable{
    
    @Override 
    public void run() { 
        // get current thread instance
        Thread t = Thread.currentThread();
        // call thread.getId() on the current t instance
        System.out.println("WorkerThread details : Name - "+ t.getName()); 
        System.out.println("Thread Id of Worker Thread - " + t.getId());
       
 
 }
}


Output :

WorkerThread details : Name - First Thread
Thread Id of Worker Thread - 7
WorkerThread details : Name - Second Thread
Thread Id of Worker Thread - 8
Executing  thread : main
id of the thread is 1
WorkerThread details : Name - Thread-1
Thread Id of Worker Thread - 9



Please mention in comments if you know any other way of getting thread ID.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry