Question:
I am trying to create a queue that will be emptied by multiple threads simultaneously. In C/C++ this requires the use of a conditional semaphore to signal that the queue is empty/not empty. How can a Condition be implemented in Java?
Answer:
Conditions are implemented in Java using the wait() and notify() methods defined in java.lang.Object. Just create an arbitrary object, such as an integer array of length one, and use that as your condition. To wait for condition, invoke its wait() method, and tosignal a condition, invoke its notify() or notifyAll() method depending on how many waiting threads you want to wake up. The thingto remember is that you must own the object’s monitor before calling either method, which requires a synchronized block.