Java Reference
In-Depth Information
final void wait( ) throws InterruptedException
final void wait(long
millis
) throws InterruptedException
final void wait(long
millis
, int
nanos
) throws InterruptedException
The first form waits until notified. The second form waits until notified or until the spe-
cified period of milliseconds has expired. The third form allows you to specify the wait
period in terms of nanoseconds.
Here are the general forms for
notify( )
and
notifyAll( )
:
final void notify( )
final void notifyAll( )
A call to
notify( )
resumes one waiting thread. A call to
notifyAll( )
notifies all threads,
with the highest priority thread gaining access to the object.
Before looking at an example that uses
wait( )
, an important point needs to be made. Al-
though
wait( )
normally waits until
notify( )
or
notifyAll( )
is called, there is a possibility
that in very rare cases the waiting thread could be awakened due to a
spurious wakeup
.
The conditions that lead to a spurious wakeup are complex and beyond the scope of this
book. However, Oracle recommends that because of the remote possibility of a spurious
wakeup, calls to
wait( )
should take place within a loop that checks the condition on which
the thread is waiting. The following example shows this technique.
An Example That Uses wait( ) and notify( )
To understand the need for and the application of
wait( )
and
notify( )
, we will create a
program that simulates the ticking of a clock by displaying the words Tick and Tock on the
screen. To accomplish this, we will create a class called
TickTock
that contains two meth-
ods:
tick( )
and
tock( )
. The
tick( )
method displays the word "Tick", and
tock( )
displays
"Tock". To run the clock, two threads are created, one that calls
tick( )
and one that calls
tock( )
. The goal is to make the two threads execute in a way that the output from the pro-
gram displays a consistent "Tick Tock"—that is, a repeated pattern of one tick followed by
one tock.