I have a Java Thread
which handles outgoing communication with a Socket
. I only want the thread to run while there is pending output ready to be sent. Say I have a Stack<String>
that holds the data waiting to be sent, I would like the comms thread to wake up when something is added to the stack and go to sleep when the stack is empty. Whats the best approach for this?
Options i see are;
wait()/notify()
- now seems to be the old way of acheiving this behaviourThread
each time (expensive)Any advice would be great :)
You can specify Timeout. Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely.
The only way to stop an arbitrary thread is by interrupting it. Keep a reference to it then call the interrupt method.
The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.
BlockingQueue
is exactly what you are looking for. Your communication thread blocks on take()
and is woken up immediately when some other thread does add
/put
.
This approach has several advantages: you can have multiple threads (consumers) sharing the same queue to increase throughput and several threads (producers) generating messages (message passing).
You could use the java.util.concurrent library, if the data structures there meet your needs. Something like BlockingQueue might work for you.
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