Java Reference
In-Depth Information
Let's suppose that the Filler thread finds that fFilled = true during
the put() method; that thread will go into a wait state. Since fFilled is true,
the Getter thread passes the fFilled test in the get() method, obtains the
fBin value, sets the fFilled flag to false , and invokes notifyAll() before
it returns. The notifyAll() method causes all threads in a wait state to attempt
to acquire the lock. When the lock is released by the Getter in the synchronized
get() method, the Filler thread can acquire the lock and continue on through
the put() method and fill the bin again.
The following code shows the Filler class. In the run() method, a loop
puts a value into the box and then pauses for a random period of time before doing
it again. For each pass of the loop, the put() invocation results in the printing
of a message via the Outputable reference.
public class Filler extends Thread
{
private Box fBox;
public Filler (Box b) {
fBox = b;
}
public void run () {
for (int i=0; i < 10; i++) {
fBox.put (i);
try {
sleep ((int)(Math.random () * 100));
}
catch (InterruptedException e) {}
}
} // run
} // class Filler
The following code shows the Getter class. The loop in its run() method will
continue until it gets ten values from the box. Note, however, that the process will
experience occasional wait states in the get() method in Box to give time for
the Filler to do its job.
public class Getter extends Thread
{
private Box fBox;
private int fNumber;
public Getter (Box b) {
fBox = b;
Search WWH ::




Custom Search