/* * ======================================================================== * CubbyHole.java : Contains the shared contents which is stored by the Producer * object and consumed by the Consumer object. In order to allow the Consumer * object to consume the contents only once as soon as the Producer object * stores the contents, the synchronized keyword is placed in the put and get methods. * * Adapted from : Campione M., Walrath K., Huml A., The Java Tutorial, 2000 * Modified by : Vasilios Lagakos March, 2001 * ========================================================================= */ public class CubbyHole { private int contents; // shared data private boolean available = false; /* Method used by the consumer to access the shared data */ public synchronized int get() { while (available == false) { try { wait(); // Consumer enters a wait state until notified by the Producer } catch (InterruptedException e) { } } available = false; notifyAll(); // Consumer notifies Producer that it can store new contents return contents; } /* Method used by the consumer to access (store) the shared data */ public synchronized void put(int value) { while (available == true) { try { wait(); // Producer who wants to store contents enters // a wait state until notified by the Consumer } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); // Producer notifies Consumer to come out // of the wait state and consume the contents } }