Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java thread wait and notify

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?

like image 630
mgamer Avatar asked May 05 '09 18:05

mgamer


People also ask

Can we override wait () or notify () methods?

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.

How wait () and notify () methods can be used with lock in thread?

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.


1 Answers

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!)

like image 64
Michael Myers Avatar answered Sep 22 '22 07:09

Michael Myers