Help: Using Threads as Actors


Help is available for each task, or you can go straight to the solution source code.

Task 1

Create the new interface Consumer, it has one method, inputItem, which has one argument, an Object, and returns no value.
Create the new interface, Consumer, with one method, whose signature is:

public void inputItem(Object o);

Task 2

Create a class that implements the Consumer interface, CatMachine. Use a WaitStack as it's input storage. The arguments to the constructor of this class should take two arguments, an integer to specify the number of stack items to look for, and a Consumer object to use as an output. The run method for this class will pop the specified number of items off the stack, concatenate them together as strings, then send them to the output consumer.
Create the CatMachine class, it extends Thread and implements the Consumer interface. It has a constructor and two methods. The constructor stores its int and Consumer arguments in instance variables, it also creates a new WaitStack and stores it in an instance variable.

One method implements the Consumer method by pushing the value of the inputItem argument onto the WaitStack. The other method is the run method, it enters a loop and tries to pop numArgs number of items off of the WaitStack, it then converts them to Strings, concatenates them, and calls the inputItem method on the output Consumer with the new result string as the argument.

Task 3

Create a subclass of TextArea that implements the Consumer interface by adding its input to its content.
Create the ConsumerTextArea class that extends TextArea and implements the Consumer interface. It's constructor takes two integer arguments, for the number of rows and columns in the text area, and calls the super class constructor with those two arguments. The only other method is the implementation of the inputItem method, which sets the content of the text area with a call to setText.

Task 4

Create a group of three CatMachines that feed the TextArea. They should be arranged so that the first two CatMachines feed the third, which in turn feeds the TextArea.
In the applet's init method, after adding the ConsumerTextArea to the layout, create three CatMachines and assign them to local variables. Set the first CatMachine to output to the ConsumerTextArea, and take two arguments. Set the second to output to the first CatMachine, and take one argument. Set the third CatMachine to output to the first, and take two arguments. Call the start methods on all of them. This sets up the lattice of machines, now they need to be fed. Call inputItem on the second CatMachine with a string argument such as "foo". Then call the inputItem method on the third CatMachine twice, each time with a different string. When the applet is run, the text area should show the result of concatenating the three strings.

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