// "Java Tech"
// Code provided with book for educational purposes only.
// No warranty or guarantee implied.
// This code freely available. No copyright claimed.
// 2003
//
/**
* Use synchronized methods to "put" and "fill"
* a bin, which holds some number passed to it.
* A flag indicates whether the bin is in a filled state
* or not.
* The put method goes into wait state if bin is filled.
* Similarly, the get method waits if bin not filled.
* When they emerge from the wait states, the processes
* do their given tasks and then invoke notifyAll () to
* wake up other threads that might be waiting on the
* object.
*
**/
public class Box {
private int fBin;
private boolean fFilled = false;
Outputable fOut;
/** Constructor obtains reference to Outputable object.**/
Box (Outputable out){
fOut = out;
}
/**
* If bin is not filled, wait for it to be.
* If bin filled, then empty it (i.e. set flag to false.)
* Notify other waiting threads that are in wait state
* on this object. Return the value in the bin.
**/
public synchronized int get () {
while (fFilled == false){
try {
wait ();
}
catch (InterruptedException e) { }
}
fFilled = false;
fOut.println ("Get value: " + fBin);
notifyAll ();
return fBin;
} // get
/**
* If bin is filled, wait for it to be emptied.
* If bin not filled, then fill it (i.e. set flag to true.)
* Notify other waiting threads that are in wait state
* on this object.
**/
public synchronized void put (int value){
while (fFilled == true) {
try {
wait ();
} catch (InterruptedException e) { }
}
fBin = value;
fFilled = true;
fOut.println ("Put value: " + fBin);
notifyAll ();
} // put
} // class Box