Using the reusable synchronization barrier Phaser : Phaser « JDK 7 « Java






Using the reusable synchronization barrier Phaser


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicInteger;

abstract class Entity implements Runnable {
  public abstract void run();
}
class WorkerA extends Entity implements Runnable {
  AtomicInteger idSource = new AtomicInteger();
  
  public void run() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
  }
  @Override
  public String toString() {
    int id = idSource.incrementAndGet();
    return "# " + id;
  }
}
class WorkB extends Entity implements Runnable {
  AtomicInteger idSource = new AtomicInteger();
  public void run() {
    try {
      Thread.sleep(400);
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
  }
  @Override
  public String toString() {
    int id = idSource.incrementAndGet();
    return "ID:" + id;
  }
}
public class Test {
  private static void gameEngine(List<Entity> entities) {
    final Phaser phaser = new Phaser(1);
    for (final Entity entity : entities) {
      final String member = entity.toString();
      System.out.println(member);
      phaser.register();
      new Thread() {
        @Override
        public void run() {
          System.out.println(member);
          phaser.arriveAndAwaitAdvance();
          entity.run();
        }
      }.start();
    }
    phaser.arriveAndDeregister();
  }

  public static void main(String[] args) {
    List<Entity> entities = new ArrayList<>();
    entities = new ArrayList<>();
    entities.add(new WorkerA());
    entities.add(new WorkB());
    gameEngine(entities);
  }
}

 








Related examples in the same category