Java 7: reusing threads? (disconnect - reconnect)

The number of threads (id) increases when the thread completes, and a new thread is created. Is Java 7 just an increasing number or am I doing something wrong?

I am building an application using Java 7, which creates a new thread on connection and then serves the connection. When the service receives a close message, it exits the loop and allows code to complete in the stream. Thus, the life of the stream supposedly ends, as I understand it (just like any object of the object). Java 7 does not use Thread.stop () or Thread.destroy () or any such thing. (Since, as I think, 5).

I have an interface with the buttons "Open connection", "Close connection" and "Send message" and the corresponding println instructions in the stream so that I can see what is happening. One of the variables I'm printing is Thread.currentThread (). When I open the first connection, currentThread () represents Thread [Thread-0,5, main]. I close the connection and exit the loop, indicating that Thread [Thread-0.5, main] is ending.

OK, so now it goes back to the square, right? There are no threads.

I reconnect and join Thread [Thread-1,5, main]. See that? "Thread-1" instead of "Thread-0". Every time I do this, the number increases by 1.

(A side question if it’s not so difficult. What does β€œ5, the main thing” mean?)

Comment re: thread stop: Why are Thread.stop, Thread.suspend and Thread.resume deprecated? .

+6
source share
3 answers

Theme-0.5, the main

0: id

5: priority

main: name

stream identifier long ; if we create a million threads per second, then after 300 thousand years id will overflow.

+2
source

The number you refer to does not mean that the current number of threads is working ... Thread- "n" is just an automatically generated number used when you do not explicitly specify a thread name. Each Thread instance that you create without a name will have a n value increased by 1. This number is used only to identify the thread instance.

However, if you use a thread pool, the task that you sent to execution can be executed in a thread that was previously used for other tasks.

Also, this is nothing special in Java 7. Java 6 has exactly the same behavior (and I suspect also previous versions).

+3
source

The number of threads (id) increases when the thread ends

Not.

and a new thread is created.

Yes.

0
source

Source: https://habr.com/ru/post/896511/


All Articles