Thread number (id) increments when thread is terminated and a new thread created. Does Java 7 just enjoy incrementing numbers or am I doing something wrong?
I'm building a service application using Java 7 that creates a new thread when a connection is made and then services the connection. When the service receives a close message, it drops out of a loop and allows completion of the code in the thread. Thus, the thread's life is supposedly terminated, as I understand it (just like any instance object). Java 7 doesn't use a Thread.stop() or Thread.destroy() or any such thing. (Not since v5 I think.)
I have an interface with buttons for "Open Connection", "Close Connection", and "Send Message" and corresponding println statements in the thread so I can see what's happening. One of the variables I print out is Thread.currentThread(). When I open the first connection, the currentThread() is Thread[Thread-0,5,main]. I close the connection and get the message out of loop indicating that Thread[Thread-0,5,main] is terminating.
OK, so now it's back to square one, right? No threads.
I click to connect again and and enter Thread[Thread-1,5,main]. See that? "Thread-1" instead of "Thread-0". Each time I do it, the number goes up by 1.
(Side question if it's not too much trouble. What's the "5,main" mean?)
Commentary re: thread stop: Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
The number you refer doesn't mean the current number of threads running... Thread-"n" is just an auto-generated number used when you don't explicitly provide a name to the thread. Each Thread
instance you create without a name, will have it's n
incremented by 1. This number is just used to identify a thread instance.
However, if you use a thread pool, the task you submitted to execution might run in a thread that was previously used for other tasks.
Also, this is nothing particular of Java 7. Java 6 had exactly the same behaviour (and I suspect also the previous versions).
Thread-0,5,main
0 : id
5 : priority
main : name
thread id is long
; if we create a million threads a second, after 300 thousand years, id will overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With