Threads
Synchronize threads
wait and notifyAll methods
Methods of the Object class for thread communication
Method | Description | wait() | Places the current thread in the Waiting state until another thread calls the notify or notifyAll method of the current object. This relinquishes the lock on the object so that other blocked threads can run. Throws InterruptedException. | notify() | Returns an arbitrary thread to the Runnable state. | notifyAll() | Returns all threads to the Runnable state so the scheduler can select one to run. |
---|
Code that waits on a condition
while (orderQueue.count() == 0) // if there are no orders ready, wait { try { wait(); } catch (InterruptedException e) {} }
Code that satisfies the condition and notifies other threads
orderQueue.add(order); // add an order to the queue notifyAll(); // notify other threads