Package test

Source Code of test.PhaserTest

package test;

import java.util.concurrent.Phaser;

public class PhaserTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    byte threadNumber = 2;
    Phaser phaser = new Phaser();
    for (byte i = 1; i <= threadNumber; i++)
      new Thread(new PhasedTask(phaser, i)).start();
   
  }

  private static class PhasedTask implements Runnable {
    byte threadNumber;
    private Phaser phaser;
    public PhasedTask(Phaser phaser, byte threadNumber) {
      this.phaser = phaser;
      this.threadNumber = threadNumber;
    }

    @Override
    public void run() {
      phaser.bulkRegister(100);
     
      // phase number is changed when arrived threads count is the same
      // as regisrered in this phaser!!!
      System.out.println(String.format("Current phase is %d", phaser.getPhase()));
     
      try {
        Thread.sleep(10000*threadNumber);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      phaser.arrive();
      System.out.println(String.format("Thread %d arrived at time %d",
          this.threadNumber, System.currentTimeMillis()));
      System.out.println(String.format("Thread %d Current phase is %d", this.threadNumber,
          phaser.getPhase()));
     
      phaser.arrive();
      System.out.println(String.format("Thread %d arrived at time %d",
          this.threadNumber, System.currentTimeMillis()));
      System.out.println(String.format("Thread %d Current phase is %d", this.threadNumber,
          phaser.getPhase()));

      try {
        Thread.sleep(10000*threadNumber);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
     
      // Waits all registered threads to come!!!
      phaser.arriveAndAwaitAdvance();
      System.out.println(String.format("Thread %d arrived at time %d",
          this.threadNumber, System.currentTimeMillis()));
      System.out.println(String.format("Current phase is %d", phaser.getPhase()));
     
      //Waits until current phase!!!
      phaser.awaitAdvance(2);
    }
   
  }
}
TOP

Related Classes of test.PhaserTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.