File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Thread Id Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread Id Problem" Watch "Thread Id Problem" New topic

Thread Id Problem

sonu raj
Ranch Hand

Joined: Jul 31, 2012
Posts: 43

When I compile and run the above program I always gets the same output:


I want to know why the output is always 9 and 10, why not 2 and 4 or 4 and 5.etc
Please elaborate!!
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Well, it's up to the JVM to decide how it wants to allocate Thread IDs. That's not fixed by the specification. So it just appears that, in this case anyway, the JVM is doing it in a way that repeats every time.

You never need to know how thread IDs are allocated when writing code. The only thing that's defined is that the ID will be constant while the thread is alive, and two alive threads will never have the same ID.
Anurag Verma
Ranch Hand

Joined: Mar 30, 2012
Posts: 128

Being a programmer we should never be concerned about this, this is allocated by JVM & the allocation is not in our control, its the JVM which is allocating it.
sonu raj
Ranch Hand

Joined: Jul 31, 2012
Posts: 43

Thank you very much!!
Sachin Bhosale

Joined: Jul 06, 2009
Posts: 7

Thread Id sequence number starts from 0. And JVM uses initial few ids (e.g. 0-8) for it's own threads. For new threads , this sequence number is incremented.

Sachin Bhosale (SCJP 1.4 | SCWCD 1.4 | SCEA 5 | IBM Certified SOA Solution Designer)
I agree. Here's the link:
subject: Thread Id Problem
It's not a secret anymore!