Date: 2019mar21
Update: 2025oct21
Language: Java
Keywords: obtain, identifier, number
Q. Java: Get ID of current thread
A. Use getId() or threadId() depending on your Java version.
As shown in this full example:
class Demo {
static class MyWonderfulThread extends Thread {
@Override public void run() {
// final long id = getId(); // Java < 19
final long id = threadId(); // Java >= 19
System.out.println("id of wonderful thread=" + id);
}
}
public static void main(String []args) {
final long id = Thread.currentThread().threadId(); // HERE
System.out.println("id of main=" + id);
MyWonderfulThread thread = new MyWonderfulThread();
thread.start();
}
}
Output (at least once):
id of main=1
id of wonderful thread=20
That is the system-assigned unique number.
If you have given a name to the thread, if can be obtained with:
String name = Thread.currentThread().getName();