THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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 notified; 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 InterruptedException, we
declare that in the throws clauseyou'll learn about InterruptedException a little later.


Looking back at the PrintServer example, you can now see that although the internal thread appears to sit
in an infinite loop, continually trying to remove jobs from the queue, the use of wait means that the thread is
suspended whenever there is no work for it to do. In contrast, if we used a queue that returned null when
empty, the printing thread would continually invoke remove, using the CPU the whole timea situation known
as busy-waiting. In a multithreaded system you very rarely want to busy-wait. You should always suspend
until told that what you are waiting for may have happened. This is the essence of thread communication with
the wait and notifyAll/notify mechanism.


14.5. Details of Waiting and Notification


There are three forms of wait and two forms of notification. All of them are methods in the Object class,
and all are final so that their behavior cannot be changed:


public final voidwait(long timeout)tHRows InterruptedException

The current thread waits until one of four things happens: notify is
invoked on this object and this thread is selected to be runnable;
notifyAll is invoked on this object; the specified timeout expires; or
the thread has its interrupt method invoked. timeout is in
milliseconds. If timeout is zero, the wait will not time out but will wait
indefinitely for notification. During the wait the lock of the object is released
and is automatically reacquired before wait completesregardless of how or
why wait completes. An InterruptedException is thrown if the wait
completes because the thread is interrupted.

public final voidwait(long timeout, int nanos)tHRows
InterruptedException

A finer-grained wait, with the time-out interval as the sum of the two
parameters: timeout in milliseconds and nanos in nanoseconds, in the
range 0999999).

public final voidwait()throws InterruptedException

Equivalent to wait(0).

public final voidnotifyAll()
Free download pdf