img
.
A Stoppable Producer/Consumer Example
Let's use the ideas above to deal with a more complex situation. Say you like the operation of the
producer/consumer model but you want to be able to start and stop at will. We'll use a shared
variable, workpile.stop, which will control the threads. If it is true, all the producers and
consumers will finish what they're doing and exit. Let's say further that we don't want the queue to
be emptied at stop time. When we decide to start up the producers and consumers again, we'll
require that the consumers empty the queue before any producers are started.
The only tricky part of this exercise is that some of the threads may be sleeping at the time we set
stop to true, and we must ensure that they are awakened so that they can exit. We must also
have the main thread sleep until the new consumers have emptied the queue. By having the
threads wait on the condition (workpile.full() && (!workpile.stop)), they can be
awakened on a change of state for either the length or stop (Code Example 6-23).
Example 6-23 Stoppable Producer/Consumer Model
public class Consumer implements Runnable {
...
public void run() {
Item item;
while (true) {
workpile.mutex.lock();
while (workpile.empty() && !workpile.stop) {
workpile.consumerCV.condWait(workpile.mutex);
}
if (workpile.stop)
break;
item = workpile.remove();
workpile.mutex.unlock();
workpile.producerCV.condSignal();
// OUTSIDE the CS
server.process(item);
}
workpile.mutex.unlock();
// Unlock!
barrier.barrierPost();
// We're exiting
}
}
public class Producer implements Runnable {
...
public void run() {
Item item;
while (true) {
item = server.get();
workpile.mutex.lock();
while (workpile.full() && !workpile.stop) {
workpile.producerCV.condWait(workpile.mutex);
}
workpile.add(item);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home