In this article, we will learn to get thread id
of a running thread in Java.
Table of Contents
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:
1 2 3 |
public long getId() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Main { public static void main(String args[]) { Thread thread = new Thread(); thread.start(); try { for (int i = 0; i < 5; i++) { System.out.println(i); Thread.sleep(500); } }catch(Exception e) { System.out.println(e); } // get thread id long id = thread.getId(); System.out.println("Thread id : "+id); } } |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Main { public static void main(String args[]) { Thread thread = new Thread(); thread.start(); try { for (int i = 0; i < 5; i++) { System.out.println(i); Thread.sleep(500); } }catch(Exception e) { System.out.println(e); } // get current thread id long id = Thread.currentThread().getId(); System.out.println("Thread id : "+id); id = thread.getId(); System.out.println("Thread id : "+id); } } |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Main { public static void main(String args[]) { Thread thread1 = new Thread(); Thread thread2 = new Thread(); Thread thread3 = new Thread(); thread1.start(); thread2.start(); thread3.start(); try { for (int i = 0; i < 5; i++) { System.out.println(i); Thread.sleep(500); } }catch(Exception e) { System.out.println(e); } // get current thread id long id = thread1.getId(); System.out.println("Thread1 id : "+id); id = thread2.getId(); System.out.println("Thread2 id : "+id); id = thread3.getId(); System.out.println("Thread3 id : "+id); } } |
Output
1
2
3
4
Thread1 id : 11
Thread2 id : 12
Thread3 id : 13
That’s all about how to get Thread Id in Java.