Java Reference
In-Depth Information
Figure 8.4
Display of
TaskSplitApplet
program. Pressing the
“Go
„
button can
result in a different sequence in the completion times of the thread each time.
8.5.3 Exclusive thread operations
Threading becomes trickier when threads perform operations that can conflict
with each other. For example, Figure 8.5 depicts a situation where two thread
processes both want to access an object but for different purposes (this is derived
from an example in the Sun Java Tutorial). The
Filler
thread wants to put
a number into the
bin
variable in the
Box
.Itcan only do so when the cav-
ity is empty. The
Getter
,onthe other hand, wants to retrieve the number
from
Cavity
and leave the
Cavity
empty. Ideally,
Filler
and
Getter
would alternate their calls to the methods
put()
and
get()
.However,ifno
special steps are taken, it is quite easy for
Getter
to invoke
get()
when
the
Cavity
is empty and for
Filler
to invoke
put()
when the
Cavity
is
still full.
This type of situation is called a
data race
because each thread is racing to
do its task without waiting for the other thread to finish its activity. A
synchro-
nization
scheme prevents this problem. Synchronization forces threads to wait
in single file at the method or code block of an object where the conflict can
occur.
In this case, this means that the
Box
object only allows one thread at a time
to invoke either its
put()
or
get()
.Itisasifonly one thread object owns the
lock
on the door to a
Box
object. That thread must give up the lock before any
other thread can access
any
synchronized method
on the object
. (Note that the
lock
terminology is by convention. Giving up the
key
might be more illuminating.
The term
monitor
is also used.)
Search WWH ::
Custom Search