I have two threads. Thread A is pulling some elements from queue and thread B is adding some elements to the queue.
I want thread A to go to sleep when the queue is empty.
When thread B adds some element to the queue it should make sure that thread A is working. How can this be done in Java?
Object declares three versions of the wait method, as well as the methods notify , notifyAll and getClass . These methods all are final and cannot be overridden.
The wait and notify methods are called on objects that are being used as locks. The lock is a shared communication point: When a thread that has a lock calls notifyAll on it, the other threads waiting on that same lock get notified.
Use a BlockingQueue
, which is:
A
Queue
that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
Seriously, don't try to reinvent the wheel here.
(If you must use wait/notify, read this tutorial. But spare yourself the pain, please!)
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