Aman birjpuriya Aman birjpuriya - 2 months ago 11
Java Question

In Multi Threading how getId Method decide ID for any thread

Thread.currentThread().getId() return thread Id in long but how thread id is decided by compiler. also there is any way set id for particular Thread .because there is no method like setId

Answer

In java 8 the thread IDs are handed out sequentially on construction of the thread (taken from the implementation of Thread):

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

As the API documentation of Thread.getId() states, the ID is promised to be unique and constant during it's lifetime:

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.

So changing the thread ID is not possible and allowing to change the ID would violate this.