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


In Java, concurrent programming often involves managing multiple threads and distinguishing them from one another. One crucial aspect of thread management is obtaining the unique identifier of the currently running thread. Knowing how to get the ID of a current running thread is essential for tasks like tracking thread behavior, synchronization, and debugging. This tutorial explores various Java methods to do just this.

Thread

Java's threads are lightweight units of execution within programs, providing parallel execution of tasks and providing one sequential flow of control within them allowing programs to carry out multiple operations concurrently. Each thread runs independently within its program while sharing memory space and resources from that same program. By taking advantage of threads, developers can achieve parallelism to enhance performance of applications.

Threads can be created by extending the Thread class or implementing its Runnable interface, and can execute concurrently, cooperatively or any combination thereof. Synchronization mechanisms like locks and semaphores may be employed to coordinate their execution without conflict between multiple threads.

class MyThread extends Thread {
   public void run() {
      // Code to be executed in the thread
   }
}

Approaches

There are various Java methods for obtaining the ID of currently running thread. Below are three commonly-used approaches:

  • Thread.currentThread().getId() method

  • Implementing Runnable method

  • Extending Thread method

Using Thread.currentThread().getId() Method

Java allows for straightforward retrieval of the ID for currently-executing threads using Thread.currentThread().getId() method. This returns an opaque long value representing its unique ID; by invoking this method within your code you can obtain this value and use it for various purposes such as differentiating between threads running within multithreaded applications, tracking execution or creating specific logic around specific threads. Overall, Thread.currentThread().getId() provides an accessible way of getting accessing thread iD for efficient thread management coordination within Java applications.

Algorithm

  • Define a function factorial(n), taking an integer value as input and returning its factorial product as output.

  • If n is 0, return 1 (base case).

  • Otherwise, use the factorial function with an integer multiplier such as 1-1 in place of multiplicative notation for multiplying with integer values of N-1.

  • Submit Results and End.

Program

public class CurrentThreadExample {
   public static void main(String[] args) {
      Thread currentThread = Thread.currentThread();
      long threadId = currentThread.getId();
      String threadName = currentThread.getName();
      System.out.println("Current thread ID: " + threadId);
      System.out.println("Current thread name: " + threadName);
   }
}

Output

Current thread ID: 1
Current thread name: main

Implementing Runnable Method

Java's Runnable interface enables developers to define and run code concurrently within different threads. By implementing it, encapsulated code that needs to run concurrently can be run using run() as its only method.

The run() method represents the entry point for every thread and contains instructions or logic which will be implemented when starting up your thread. Here you can define any desired behavior such as performing calculations, accessing shared resources or performing an array of tasks.

Algorithm

  • Initialize Factorial as 1. and read the number input n

  • If n is less than zero, display an error message and exit.

  • If n is zero or one, its factorial is one and you should display and exit.

  • Multiply factorial by i, which must range between two and nine.

  • Present the factorial as the result.

Program

public class CurrentThreadExample implements Runnable {
   public void run() {
      long threadId = Thread.currentThread().getId();
      String threadName = Thread.currentThread().getName();
      System.out.println("Current thread ID: " + threadId);
      System.out.println("Current thread name: " + threadName);
   }

   public static void main(String[] args) {
      CurrentThreadExample example = new CurrentThreadExample();
      Thread thread = new Thread(example);
      thread.start();
   }
}

Output

Current thread ID: 32
Current thread name: Thread-0

Extending Thread Method

Extending the Java Thread class enables you to create a customized class with all the properties and methods of the Thread class inherited by it, including its run() method for managing runaway threads. By extending Thread, you can override this method for individual threads with specific characteristics defining how they will behave during run() calls.

Extension of the Thread class makes obtaining the ID of an ongoing thread much simpler as you can access its getId() method directly without creating separate instances and passing Runnable objects as input parameters. When retrieving its ID directly via overridden run() methods or calling Thread.currentThread().getId() from within overridden methods you will easily obtain its identity.

Algorithm

  • Read in input number n and create a custom class which extends Thread class.

  • Substitute the run() method in your custom class.

  • Within the run() method, initialize factorial as 1.

  • If n is less than 0, an error message and exit will be generated.

  • If n = 0, 1, 2, or 3, display and exit.

  • Repeat from 2 to n iterations while multiplying factorial by current number during each iteration.

  • Display the final value of factorial as the result.

  • Create an instance of the custom class.

  • Begin a new thread using the start() method.

Program

public class CurrentThreadExample extends Thread {
   public void run() {
      long threadId = this.getId();
      String threadName = this.getName();
      System.out.println("Current thread ID: " + threadId);
      System.out.println("Current thread name: " + threadName);
   }

   public static void main(String[] args) {
      CurrentThreadExample example = new CurrentThreadExample();
      example.start();
   }
}

Output

Current thread ID: 32
Current thread name: Thread-0

Conclusion

In this tutorial, we have discovered how to obtain the ID of currently running thread in Java by employing different techniques. By doing this, developers are given an ability to distinguish threads within a concurrent program by retrieving their thread ID; tracking thread behavior for analysis or debugging multithreaded applications may become possible as well as implement specific logic related to them. Understanding and employing such approaches enables developers to effectively leverage threads when developing Java applications.

Updated on: 25-Jul-2023

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements