Java – get threads waiting indefinitely

I have a java thread to handle outgoing communication with the socket I just want the thread to run, and the pending output is ready to be sent Say I have a stack < string > which stores the data waiting to be sent. I want the communication thread to wake up when adding something to the stack and enter the sleep state when the stack is empty Is this the best way?

The options I see are

>Use wait () / notify () – now seems to be the old way of this behavior > if there is anything to send, perform thread checking every x milliseconds, build a new thread each time (expensive) keep the thread running (expensive) > implement some thread pool or actuator solutions

Any suggestion would be great:)

Solution

BlockingQueue is exactly what you are looking for Your communication thread is blocked on take (). When some other thread is added / placed, it will be awakened immediately

This approach has several advantages: you can have multiple threads (consumers) sharing the same queue to increase throughput and multiple threads (producers) generating messages (messaging)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>