Java Reference
In-Depth Information
/** Create Filler and Getter thread instances and start
* them filling and getting from a Box instance. **/
public void start () {
Box b = new Box (this);
Filler f1 = new Filler (b);
Getter b1 = new Getter (b);
f1.start ();
b1.start ();
} // start
...
} // class ExclusiveApplet
8.5.4 Communications among threads
In the previous section, we discussed the case where multiple threads try to access
an object and can step on each other if not properly synchronized. Here we look
at the even trickier situation where a thread needs to access data in another thread
and must also avoid a data race situation.
The standard example for communicating threads is the
producer/consumer
paradigm. The producer object invokes its own synchronized method to create
the data of interest. The consumer cannot invoke the producer's
get()
method,
which is also synchronized, until the producer has finished with its creation
method. The producer, in effect, locks its own door to the consumer until it
finishes making the data. (Imagine a physical store that locks its doors and does
not allow shoppers in while restocking the shelves.) Similarly, while the consumer
gets the data from the producer, it obtains the
lock
and prevents the producer from
generating more data until the consumer is finished.
Below we illustrate this paradigm with a program in which the
Sensor
class
represents the producer thread and
DataGetter
represents the consumer thread.
An instance of
Sensor
obtains its data (here just clock readings) in a loop in
run()
via calls to the synchronized
sense()
method. The data goes into a
buffer array. A thread can invoke
get()
in
Sensor
to obtain the oldest data in
the buffer. The indices are set up to emulate a FIFO (First-In-First-Out) buffer.
When the buffer is full, the
Sensor
thread waits for data to be read out (that is,
it gives up the lock by calling the
wait()
method).
To obtain the data, a
DataGetter
instance invokes the synchronized
get()
method in the
Sensor
instance. If no new data is available, it will give up the
lock and wait for new data to appear (that is, when
notifyAll()
is invoked in
the
sense()
method).
This snippet from
DataSyncApplet
creates the sensor and starts it. Then a
DataGetter
is created and started.
Search WWH ::
Custom Search