Java Phaser get information

Description

Java Phaser get information

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

class Task implements Runnable {
  private Phaser phaser;

  public Task(Phaser phaser) {
    this.phaser = phaser;
  }//from  w  w  w  . j ava  2 s . c  o  m

  @Override
  public void run() {
    phaser.arrive();
    System.out.println("phase 1:"+ Thread.currentThread().getName());
    try {
      TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Finishing phase:"+ Thread.currentThread().getName());

    phaser.arriveAndAwaitAdvance();

    System.out.println("Entering phase 2:"+ Thread.currentThread().getName());
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Finishing phase 2:"+ Thread.currentThread().getName());

    phaser.arriveAndAwaitAdvance();

    System.out.println("Entering phase 3:"+ Thread.currentThread().getName());
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Finishing phase 3:"+ Thread.currentThread().getName());

    phaser.arriveAndDeregister();
  }
}

public class Main {

  public static void main(String[] args) throws Exception {

    Phaser phaser = new Phaser(3);

    for (int i = 0; i < 3; i++) {
      Task task = new Task(phaser);
      Thread thread = new Thread(task);
      thread.start();
    }

    for (int i = 0; i < 10; i++) {
      System.out.printf("Phase: %d\n", phaser.getPhase());
      System.out.printf("Registered Parties: %d\n", phaser.getRegisteredParties());
      System.out.printf("Arrived Parties: %d\n", phaser.getArrivedParties());
      System.out.printf("Unarrived Parties: %d\n", phaser.getUnarrivedParties());

      TimeUnit.SECONDS.sleep(1);
    }
  }
}



PreviousNext

Related