Java Phaser execute a specific number of phases

Introduction

We can override onAdvance() to execute a specific number of phases and then stop.

import java.util.concurrent.Phaser;

class MyPhaser extends Phaser {
  int numPhases;/*from  w  w w .ja v  a 2s.c om*/

  MyPhaser(int parties, int phaseCount) {
    super(parties);
    numPhases = phaseCount - 1;
  }

  protected boolean onAdvance(int p, int regParties) {
    System.out.println("Phase " + p + " completed.\n");

    // If all phases have completed, return true
    if (p == numPhases || regParties == 0)
      return true;

    // Otherwise, return false.
    return false;
  }
}

public class Main {
  public static void main(String args[]) {

    MyPhaser phsr = new MyPhaser(1, 4);

    System.out.println("Starting\n");

    new MyThread(phsr, "A");
    new MyThread(phsr, "B");
    new MyThread(phsr, "C");

    // Wait for the specified number of phases to complete..
    while (!phsr.isTerminated()) {
      phsr.arriveAndAwaitAdvance();
    }

    System.out.println("The Phaser is terminated");
  }
}

// A thread of execution that uses a Phaser.
class MyThread implements Runnable {
  Phaser phsr;
  String name;

  MyThread(Phaser p, String n) {
    phsr = p;
    name = n;
    phsr.register();
    new Thread(this).start();
  }

  public void run() {

    while (!phsr.isTerminated()) {
      System.out.println("Thread " + name + " Beginning Phase " + phsr.getPhase());

      phsr.arriveAndAwaitAdvance();
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
        System.out.println(e);
      }
    }

  }
}



PreviousNext

Related