Java - Bulk register task to Phaser

Introduction

You can do bulk task register to Phaser using bulkRegister method.

Demo

import java.util.concurrent.Phaser;

class MyTask extends Thread {
  private Phaser phaser;
  private String taskName;

  public MyTask(String taskName, Phaser phaser) {
    this.taskName = taskName;
    this.phaser = phaser;
  }/*w  w  w  . j  a  v  a2  s  .  c o  m*/

  @Override
  public void run() {
    System.out.println(taskName + ":Initializing...");

    int sleepTime = 3;
    try {
      Thread.sleep(sleepTime * 1000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(taskName + ":Initialized...");
    // Wait for all parties to arrive to start the task
    phaser.arriveAndAwaitAdvance();
    System.out.println(taskName + ":Started...");
  }
}

public class Main {
  public static void main(String[] args) {
    Phaser phaser = new Phaser();
    final int TASK_COUNT = 3;
    phaser.bulkRegister(TASK_COUNT);
    for (int i = 1; i <= TASK_COUNT; i++) {
      String taskName = "Task #" + i;
      MyTask task = new MyTask(taskName, phaser);
      task.start();
    }
  }
}

Result

Related Topic