for (int j = 0; j < 3; j++) {
System.out.println("Starting consumers...  List length: " +
workpile.length());
for (int i = 0; i < nConsumers; i++) {
t = new Thread(new Consumer(workpile, s, barrier));
t.start();
}
workpile.mutex.lock();
while (!workpile.empty())
workpile.producerCV.condWait(workpile.mutex);
workpile.mutex.unlock();
System.out.println("Starting producers...List length: " +
workpile.length());
for (int i = 0; i < nProducers; i++) {
t = new Thread(new Producer(workpile, s, barrier));
t.start();
}
new Thread(new Stopper(workpile, 5000)).start();
barrier.barrierWait();
System.out.println("Stopped! List length:" +
workpile.length());
workpile.stop = false;
InterruptibleThread.sleep(2000);
}
System.out.println("Finished!  Produced: " + s.pcounter
+ " Consumed: " + s.ccounter
+ " items. List length: " + workpile.length());
System.exit(0);
}
A minor point: When we set stop = false, we don't have to lock the mutex. Why can we get
away with this?
We can do this because we wrote the program and we happen to know that there are no other
threads running by the time we get to this line, so for one brief moment, stop is not a shared
variable. In production code it would be well advised to protect it anyway-- no sense in making
someone else wonder about it.
APIs Used in This Chapter
The Class java.lang.Object
synchronized
synchronized
This language keyword causes the current thread to obtain the hidden lock for the object. If the
lock is already held by the current thread, it will essentially increment a counter for that lock (it's a
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home