How to Get Id of a Thread in Java Tutorial

In this section, we will learn how to get the id value of a thread in Java.

Java Thread getId() Method

Each thread in a Java program has an id associated with it. We can get this id number by calling a method of the Thread class that is called getId() method.

Java Thread getId() syntax

public long getId()

Java Thread getId() parameters

The method does not take an argument.

Java Thread getId() Return Value

The return value of this method is of type long and it is the id of the target thread (the one that invoked the method).

Java Thread getId() Exception:

The method does not throw an exception.

Example: using Java Thread getId() method

public class Main {

    public static void main(String[] args) {
        System.out.println("The name of the thread is: "+Thread.currentThread().getName());
        System.out.println("The id of the main thread is: "+Thread.currentThread().getId());

        System.out.println("***************");
        Thread thread = new Thread("Thread-One");
        System.out.println("The name of the thread is: "+ thread.getName());
        System.out.println("The id of the thread is: "+ thread.getId());
    }

}

Output:

The name of the thread is: main

The id of the main thread is: 1

***************

The name of the thread is: Thread-One

The id of the thread is: 18
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies