Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: s/4/MAX_STEPS-1/

...

Code Block
bgColor#ccccff
// Declare class as final because its constructor throws an exception 
public final class ProcessStep implements Runnable { 
  private static final Lock lock = new ReentrantLock();
  private static int time = 0;
  private final int step; // Do operations when the step reaches this value
  private static final int MAX_STEPS = 5;
  private static final Condition[] conditions = new Condition[MAX_STEPS];

  public ProcessStep(int step) {
    if (step <= MAX_STEPS) {
      this.step = step;
      conditions[step] = lock.newCondition();
    } else {
      throw new IllegalArgumentException("Too many threads");
    }
  }

  public void run() {
    lock.lock();
    try {
      while (time != step) { 
        conditions[step].await();  
      }

      // ... Do operations

      time++;
      if (step + 1 < conditions.length) {
        conditions[step + 1].signal();
      }
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt(); // Reset interrupted status
    } finally {
      lock.unlock();
    }
  }

  public static void main(String[] args) {
    for (int i = 4MAX_STEPS - 1; i >= 0; i--) {
      ProcessStep ms = new ProcessStep(i);
      new Thread(ms).start();
    }
  }
}

...