Printing W, X, Y, and Z

Program 4.3 uses semaphores to synchronize three threads so they print out the letters `A', `B', and `C' according to certain rules. Your task in this programming assignment is to synchronize four threads so they print out the letters `W', `X', `Y', and `Z' according to the following rules.

  1. The total number of `W's and `X's that have been output at any point in the output string cannot exceed the total number of `Y's and `Z's that have been output at that point.
  2. The total number of `W's that have been output at any point in the output string cannot exceed twice the number of `X's that have been output at that point.
  3. After a `Y' has been output, another `Y' cannot be output until one or more `Z's have been output.

Use a single monitor object instantiated from a class Control for synchronization. Do not mechanically translate semaphore code into monitor code! Each of the four printing threads invokes a synchronized monitor method for its synchronization. No semaphores allowed. No synchronized blocks allowed, only synchronized methods. No busy waiting allowed. No calls to nap inside a synchronized method allowed (do not nap while holding the monitor object's lock, that is, while inside a synchronized method or while inside a method called by a synchronized method). Do you see why?

Input Data

The input data consists of five integer (int) numbers: w, x, y, z, and runtime. You must parse these five numbers from the command line using the GetOpt class (Library Class 2.1). The command line has the form

    % java WXYZs -w w -x x -y y -z z -R runtime
Remember to give the corresponding variables default values in your program to handle missing command line options.

The numbers w, x, y, and z control the napping time of the four threads printing the corresponding letter, as follows.

class Pw extends ... implements Runnable {
   public void run () {
      while (true) {
         int napping = 1+(int)random(1000*w); // w is in seconds
         nap(napping);

         ...    // synchronization to follow the rules

         System.out.print("W"); System.out.flush();

         ...    // synchronization to follow the rules
      }
   }
}
Before each time a thread prints a letter (according to the rules), it naps for a random number of milliseconds generated from its command line argument (in seconds) or its default value. The number runtime controls how long the whole program runs, i.e., there is a nap(1000*runtime) in the main method.

Animate your program using XtangoAnimator.