Java Reference
In-Depth Information
First, notice that
tick( )
is modified by
synchronized
. Remember,
wait( )
and
notify( )
ap-
ply only to synchronized methods. The method begins by checking the value of the
run-
ning
parameter. This parameter is used to provide a clean shutdown of the clock. If it is
false
, then the clock has been stopped. If this is the case,
state
is set to "ticked" and a call
to
notify( )
is made to enable any waiting thread to run. We will return to this point in a
moment.
Assuming that the clock is running when
tick( )
executes, the word "Tick" is displayed,
state
is set to "ticked", and then a call to
notify( )
takes place. The call to
notify( )
allows
a thread waiting on the same object to run. Next,
wait( )
is called within a
while
loop. The
call to
wait( )
causes
tick( )
to suspend until another thread calls
notify( )
. Therefore, the
loop will not iterate until another thread calls
notify( )
on the same object. As a result, when
tick( )
is called, it displays one "Tick", lets another thread run, and then suspends.
The
while
loop that calls
wait( )
checks the value of
state
, waiting for it to equal
"tocked", which will be the case only after the
tock( )
method executes. As explained, using
a
while
loop to check this condition prevents a spurious wakeup from incorrectly restarting