|
|
|
|||
|
Synchronizing ThreadsTheProducer generates an integer
between 0 and 9 (inclusive), stores it in a
CubbyHole object, and prints the
generated number. To make the synchronization problem more
interesting, the Producer sleeps for a random amount of time between 0 and
100 milliseconds before repeating the number generating cycle:
The Consumer, being ravenous,
consumes all integers from the CubbyHole (the exact same object into
which the Producer put the integers in the first place) as quickly
as they become available.
The Producer and Consumer in this example share data through
a common CubbyHole object. And you will note
that neither the Producer nor the Consumer makes any effort whatsoever
to ensure that the Consumer is getting each value produced once
and only once. The synchronization between these two threads actually
occurs at a lower level, within the get and put
methods of the CubbyHole object. However, let's assume for a moment that
these two threads make no arrangements for synchronization and talk about
the potential problems that might arise in that situation.
One problem arises when the
Another problem that might arise is when the Consumer is quicker than
the Producer and consumes the same value twice. In this situation, the Consumer
would print the same value twice and might produce output that looked like this:
Either way, the result is wrong. You want the Consumer to get each
integer produced by the Producer exactly once.
Problems such as those just described are called race conditions.
They arise from multiple, asynchronously executing threads trying to
access a single object at the same time and getting the wrong result.
Race conditions in the producer/consumer example are prevented by
having the storage of a new integer
into the
The activities of the
And second, the two threads must do some simple coordination. That is,
the The Main ProgramHere's a small stand-alone Java application that creates a The OutputHere's the output of ProducerConsumerTest.Producer #1 put: 0 Consumer #1 got: 0 Producer #1 put: 1 Consumer #1 got: 1 Producer #1 put: 2 Consumer #1 got: 2 Producer #1 put: 3 Consumer #1 got: 3 Producer #1 put: 4 Consumer #1 got: 4 Producer #1 put: 5 Consumer #1 got: 5 Producer #1 put: 6 Consumer #1 got: 6 Producer #1 put: 7 Consumer #1 got: 7 Producer #1 put: 8 Consumer #1 got: 8 Producer #1 put: 9 Consumer #1 got: 9 | |||
|