Activity 8.6 - Running the greedy consumers

Topic

This activity uses the methods wait() and notifyAll() which all classes inherit from Object.

Materials

In addition to the Solution document, the project for this activity contains three classes:

Task

Class SweetJar models a container for sweets and has:

Class Consumer extends Thread and models a greedy sweet lover who will just keep eating sweets as long as any are left in the jar.

Class Main creates a jar with 20 sweets in, then creates two consumer threads and sets them executing. These consumer threads will compete with one another, each attempting to grab as many as possible of the 20 sweets.

In its current form, the program allows the running thread to go on gobbling up sweets one after another, and possibly consume them all before the other thread can even get a look in.

The objective is to amend the class SweetJar so that the two threads must take turns to eat just one sweet at a time, thus ensuring a fair distribution.

Instructions

Run the program.

Notice that because the two threads are uncoordinated at the moment the thread that first gets to run will swallow up most of the 20 sweets (perhaps all of them) before the other thread can get a look in. Our output began like this:

Consumer 1 eats sweet 20 - yummy!
Consumer 1 eats sweet 19 - yummy!
Consumer 1 eats sweet 18 - yummy!
Consumer 1 eats sweet 17 - yummy!
Consumer 1 eats sweet 16 - yummy!
Consumer 1 eats sweet 15 - yummy!
Consumer 1 eats sweet 14 - yummy!
Consumer 1 eats sweet 13 - yummy!
Consumer 1 eats sweet 12 - yummy!
Consumer 1 eats sweet 11 - yummy!
Consumer 1 eats sweet 10 - yummy!
Consumer 1 eats sweet 9 - yummy!

As you see, the first consumer has already eaten more than half the contents of the jar!

To prevent this greedy behaviour you will need to change the class SweetJar as follows: