Using Wait and Notify in a Producer/Consumer Scenario


In this Magercise, a SimpleStack is modified to make it more useful in a concurrent environment. The new stack, WaitStack, makes threads attempting to pop items off the stack wait when the stack is empty and notifies them when a new item has been pushed onto the stack.

The WaitStack acts as a communication channel between threads. Those that pop items off the stack are consumers, and those that push items on are producers.

Work Location

Perform all work for this magercise in VisualAge project MageLang Magercises, package magercises.Using Wait and Notify.

If this project does not appear in your Workspace add it from the repository (if it exists there) or create a new project using this name.

Tasks

Perform the following tasks:

  1. Modify the SimpleStack to make threads calling pop to wait then the stack is empty.

  2. Modify the push method to notify all waiting threads. Rename SimpleStack to WaitStack.

  3. Create two new classes, StackPusher, which acts a producer task by repeatedly pushing an item onto the stack, and StackPopper, which acts as a consumer, and repeatedly pops items off the stack. As the last thing in the run method of both classes, make a call to StackTest.threadDone to print the stack to the output TextArea. The StackTest Applet class shows how the constructors of these classes should look.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.