Java Reference
In-Depth Information
Otherwise you must use notifyAll . If a subclass violates either of the
first two conditions, code in the superclass that uses notify may well
be broken. To that end it is important that waiting and notification
strategies, which include identifying the reference used ( this or some
other field), are documented for use by extended classes.
The following example implements the PrintQueue class that we used
with the PrintServer on page 343 . We reuse the SingleLinkQueue class
that we defined in Chapter 11 to actually store the print jobs, and add
the necessary synchronization:
class PrintQueue {
private SingleLinkQueue<PrintJob> queue =
new SingleLinkQueue<PrintJob>();
public synchronized void add(PrintJob j) {
queue.add(j);
notifyAll(); // Tell waiters: print job added
}
public synchronized PrintJob remove()
throws InterruptedException
{
while (queue.size() == 0)
wait(); // Wait for a print job
return queue.remove();
}
}
In contrast to SingleLinkQueue itself, the methods are synchronized to
avoid interference. When an item is added to the queue, waiters are no-
tified; and instead of returning null when the queue is empty, the remove
method waits for some other thread to insert something so that take
will block until an item is available. Many threads (not just one) may
be adding items to the queue, and many threads (again, not just one)
may be removing items from the queue. Because wait can throw Inter-
 
Search WWH ::




Custom Search