开发者

Java 7: Thread reuse? (disconnect - reconnect)

开发者 https://www.devze.com 2023-04-02 16:15 出处:网络
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?

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 o开发者_Go百科f 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.


Thread number (id) increments when thread is terminated

No.

and a new thread created.

Yes.

0

精彩评论

暂无评论...
验证码 换一张
取 消