Skip to content
Related Articles

Related Articles

Improve Article

How to Get the Id of a Current Running Thread in Java?

  • Last Updated : 11 Nov, 2020

The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.

Java allows concurrent execution of different parts of a program with the help of threads. Multithreading in Java is achieved by extending the Thread class or implementing the Runnable Interface. Since multiple inheritance is not allowed in Java it is recommended to implement the Runnable interface for thread creation so that if required the class implementing the Runnable interface can extend some other class. In this article, we have demonstrated both the methods of creating a thread. The first approach shows thread creation by extending the Thread class and the second approach shows thread creation by implementing the Runnable Interface.

Declaration

public long getId()

Return value: This method returns the ID of a thread.

Approach 1: Following are the steps to create a thread by extending the Thread class.



  1. ThreadDemo1 class extends the Thread class and overrides the run() method of Thread class.
  2. In the run() method, we use the currentThread().getName() method to get the name of the current thread that has invoked the run() method.
  3. We use the currentThread().getId() method to get the id of the current thread that has invoked the run() method.
  4. Within the main() method, two instances of the ThreadDemo1 class is created.
  5. t1 and t2 are two threads which invoke the start() method.
  6. Invoking the start() method basically invokes the run() method by default.
  7. join() method is used to prevent t2 from running before the completion of t1.
  8. As soon as t1 completes t2 begins execution.

Example:

Java




// Java program to get the id of a 
// thread
  
import java.util.*;
public class ThreadDemo1 extends Thread {
    public void run()
    {
        // gets the name of current thread
        System.out.println(
            "Current Thread Name: "
            + Thread.currentThread().getName());
        
        // gets the ID of the current thread
        System.out.println(
            "Current Thread ID: "
            + Thread.currentThread().getId());
    }
    public static void main(String[] args)
        throws InterruptedException
    {
        Scanner s = new Scanner(System.in);
        
        // creating first thread
        ThreadDemo1 t1 = new ThreadDemo1();
        
        // creating second thread
        ThreadDemo1 t2 = new ThreadDemo1();
        
        // Starting the thread
        t1.start();
        t2.start();
        
        // t2 does not start execution until t1 completes
        // execution
        t1.join();
    }
}
Output
Current Thread Name: Thread-0
Current Thread Name: Thread-1
Current Thread ID: 11
Current Thread ID: 12

Approach 2: In the second approach, the thread is created by implementing the Runnable Interface.

  1. ThreadDemo2 class implements the Runnable interface and overrides the run() method.
  2. A runnable instance of ThreadDemo2 class t is created.
  3. Two instances of the Thread class are created by passing the runnable instance as the first parameter and the name of the thread as the second parameter
  4. start() method is invoked on both the threads
  5. start() method invokes the run() method by default

Example:

Java




// Java program to get the id of a 
// thread
  
public class ThreadDemo2 implements Runnable {
    public void run()
    {
        // gets the name of current thread
        System.out.println(
            "Current Thread Name: "
            + Thread.currentThread().getName());
        
        // gets the ID of the current thread
        System.out.println(
            "Current Thread ID: "
            + Thread.currentThread().getId());
    }
    public static void main(String[] args)
    {
          // Runnable target
        ThreadDemo2 t = new ThreadDemo2();
        
          // create threads
        Thread t1 = new Thread(t, "First Thread");
        Thread t2 = new Thread(t, "Second Thread");
            
          // start threads
        t1.start();
        t2.start();
    }
}
Output
Current Thread Name: First Thread
Current Thread Name: Second Thread
Current Thread ID: 11
Current Thread ID: 12

Note: The output may vary for the second approach as it is not synchronized and the threads execute concurrently. So the order in which the thread name or thread id is printed may vary. To prevent this problem we used join() method in the first approach. If the order of the printed output is to be maintained then the user can use the join() method.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :