Get Thread Id in Java

Previous
Next

In this article, we will learn to get thread id of a running thread in Java.


An Id is a unique positive number generated at the time of thread creation. This id remains unchanged during the lifetime of the thread. When a thread gets terminated its id can be used to refer another thread, but two threads can not have same id number at the same time.

To get thread id, Java Thread class provides a method getId() that returns a long type value as id number.
The syntax of the method is given below:

Get Thread Id in Java

In this example, we created and started a thread. After that, by using getId() method, we get thread id. See the example below.

Output

0
1
2
3
4
Thread id : 11

Get Thread Id of Current Running Thread

If we want to get id of current runnig thread, then by using the currentThread() method we can call getId() method. See the example below.

Output

0
1
2
3
4
Thread id : 1
Thread id : 11

Get Thread id of Multiple Threads

Java allows to create multiple threads, in that case we can get threat id of individual threat by calling getId() method. See the example below.

Output

0
1
2
3
4
Thread1 id : 11
Thread2 id : 12
Thread3 id : 13

That’s all about how to get Thread Id in Java.

Previous
Next


Related posts

Add Comment