Java Reference
In-Depth Information
the thread. If
state
does not equal "tocked" when
wait( )
returns, it means that a spurious
wakeup occurred, and
wait( )
is simply called again.
The
tock( )
method is an exact copy of
tick( )
except that it displays "Tock" and sets
state
to "tocked". Thus, when entered, it displays "Tock", calls
notify( )
, and then waits.
When viewed as a pair, a call to
tick( )
can only be followed by a call to
tock( )
, which can
only be followed by a call to
tick( )
, and so on. Therefore, the two methods are mutually
synchronized.
The reason for the call to
notify( )
when the clock is stopped is to allow a final call to
wait( )
to succeed. Remember, both
tick( )
and
tock( )
execute a call to
wait( )
after dis-
playing their message. The problem is that when the clock is stopped, one of the methods
will still be waiting. Thus, a final call to
notify( )
is required in order for the waiting meth-
od to run. As an experiment, try removing this call to
notify( )
and watch what happens.
As you will see, the program will “hang,” and you will need to press CTRL-C to exit. The
reason for this is that when the final call to
tock( )
calls
wait( )
, there is no corresponding
call to
notify( )
that lets
tock( )
conclude. Thus,
tock( )
just sits there, waiting forever.
Before moving on, if you have any doubt that the calls to
wait( )
and
notify( )
are ac-
tually needed to make the “clock” run right, substitute this version of
TickTock
into the
preceding program. It has all calls to
wait( )
and
notify( )
removed.