What is thread getid() in Java?

The Thread class in Java

From the java.lang* package, Thread is a major class in Java on which a multithreading system is based.

In Java, we can use this class to process and work with threads and runnable interface.

The getid() method

The getid() function from the Thread class is used to extract a unique thread ID. This unique identifier is assigned when we create a new thread in our program.

Syntax


long getId()

Parameters

This function does not accept parameter values.

Return value

  • Thread_ID: It returns this thread ID of primitive long type.

Code

In the code snippet below, we have two threads: one is EdPresso (main thread), and another is thread in line 10.

We are using a runnable interface for the proper execution of threads. These threads have their unique IDs associated with them.

Execute this code to check unique identifiers or thread IDs on the console.

// Load Thread class from
// java.lang package
import java.lang.Thread;
// main program
public class EdPresso {
public static void main(String[] args) {
System.out.println("Main thread ID: "
+ Thread.currentThread().getId());
Thread thread = new Thread(new EdPresso().
new Runnabledemo());
thread.start();
}// runnable interface class
private class Runnabledemo implements Runnable {
public void run()
{
System.out.println("In run() method: " + Thread.currentThread().getId());
}
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources