Java Reference
In-Depth Information
} // ctor
/** If bin is not filled, wait for it to be. **/
public synchronized int get () {
while (!fFilled) {
try {
wait ();
}
catch (InterruptedException e) {}
}
fFilled = false;
fOutput.println ("Get value:" + fBin);
notifyAll ();
return fBin;
} // get
/** If bin is filled, wait for it to be emptied. **/
public synchronized void put (int value) {
while (fFilled) {
try {
wait ();
}
catch (InterruptedException e) {}
}
fBin = value;
fFilled = true;
fOutput.println ("Put value: " + fBin);
notifyAll ();
} // put
} // class Box
We want to emphasize that each instance of Box has its own lock. There is no
interference problem among different Box objects. If a thread owns the lock on
one Box object, this does not prevent another thread from owning the lock on a
different Box object.
This code also illustrates the wait() and notifyAll() methods. When a
thread invokes put() or get() ,itwill wait until it is granted the lock for that
object because of the presence of the synchronized keyword. Once the thread
is granted the lock, it continues on through the method. Inside the method, a
check is made on the fFilled flag. When attempting a put() ,if fFilled is
already true (i.e. if the bin is already full), then an explicit wait() is invoked.
Similarly, during a get() ,if fFilled is false (i.e. if the bin is empty), then
wait() is invoked. Invoking wait() means that the thread gives up the lock
and remains at that point in the method until notified to continue.
 
Search WWH ::




Custom Search