Java Phaser add entity

Description

Java Phaser add entity

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

public class Main {
   private void execute() {
      List<Entity> entities = new ArrayList<>();
      entities = new ArrayList<>();
      entities.add(new Developer());
      entities.add(new Tester());
      entities.add(new Tester());
      entities.add(new Tester());
      gameEngine(entities);//from w w w.j  a va2  s  .c o m
   }

   private 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 + " joined the company");
         phaser.register();
         new Thread() {
            @Override
            public void run() {
               System.out.println(member + " waiting for the remaining employees");
               phaser.arriveAndAwaitAdvance(); // wait for remaining entities
               System.out.println(member + " starting run");
               entity.run();
            }
         }.start();
      }
      phaser.arriveAndDeregister(); // unregister and continue
      System.out.println("Phaser continuing");
   }

   public static void main(String[] args) {
      new Main().execute();
   }

}

abstract class Entity implements Runnable {
   public abstract void run();
}

class Developer extends Entity implements Runnable {
   private final static AtomicInteger idSource = new AtomicInteger();
   private final int id = idSource.incrementAndGet();

   public void run() {
      System.out.println(toString() + " started");
      try {
         Thread.currentThread().sleep(ThreadLocalRandom.current().nextInt(200, 600));
      } catch (InterruptedException ex) {
         ex.printStackTrace();
      }
      System.out.println(toString() + " stopped");
   }

   @Override
   public String toString() {
      return "Developer #" + id;
   }
}

class Tester extends Entity implements Runnable {
   private final static AtomicInteger idSource = new AtomicInteger();
   private final int id = idSource.incrementAndGet();

   public void run() {
      System.out.println(toString() + " started");
      try {
         Thread.currentThread().sleep(ThreadLocalRandom.current().nextInt(400, 800));
      } catch (InterruptedException ex) {
         ex.printStackTrace();
      }
      System.out.println(toString() + " stopped");
   }

   @Override
   public String toString() {
      return "Tester #" + id;
   }
}



PreviousNext

Related