Thread getId() method in Java

Method declaration – public Long getId().

This method returns long value as thread’s id.

public class ThreadExample extends Thread {
    public static void main(String[] args) {
        System.out.print(Thread.currentThread().getId());
    }
}

Output is – 1

Every thread in java has a unique id. Even we define custom thread JVM allocates a thread id for that thread.


package multithreading;

public class ThreadExample extends Thread {

	public static void main(String[] args) {
		Thread thread1 = new Thread() {
			public void run() {
				System.out.println("Thread id is :- "+Thread.currentThread().getId());
			}
		};
		
		thread1.start();
		
		Runnable r = new Runnable() {
			public void run() {
				System.out.println("Thread id is :- "+Thread.currentThread().getId());
			}
		};
 
		
		Thread thread2 = new Thread(r);
		thread2.start();
		
	}

}

Output is –


Thread id is :- 8
Thread id is :- 9