CountDownLatch countDownLatch = new CountDownLatch(12); //count deregister parties after all //parties count is 12 all the times //if you want change the number of parties, you should create a new instance. CyclicBarrier cyclicBarrier =new CyclicBarrier(12);
voidrunTasks(List<Runnable> tasks){ final Phaser phaser = new Phaser(1); // "1" to register self // create and start threads for (final Runnable task : tasks) { phaser.register(); new Thread() { @Override publicvoidrun(){ phaser.arriveAndAwaitAdvance(); // await all creation task.run(); } }.start(); }
// allow threads to start and deregister self phaser.arriveAndDeregister(); }
voidstartTasks(List<Runnable> tasks, finalint iterations){ final Phaser phaser = new Phaser() { @Override protectedbooleanonAdvance(int phase, int registeredParties){ return phase >= iterations || registeredParties == 0; } }; phaser.register(); for (final Runnable task : tasks) { phaser.register(); new Thread() { @Override publicvoidrun(){ do { task.run(); phaser.arriveAndAwaitAdvance(); } while (!phaser.isTerminated()); } }.start(); } phaser.arriveAndDeregister(); // deregister self, don't wait }
voidawaitPhase(Phaser phaser, int phase){ int p = phaser.register(); // assumes caller not already registered while (p < phase) { if (phaser.isTerminated()) { // ... deal with unexpected termination } else { p = phaser.arriveAndAwaitAdvance(); } } phaser.arriveAndDeregister(); }
API
构造器
public Phaser()
Creates a new phaser with no initially registered parties, no parent, and initial phase number 0. Any thread using this phaser will need to first register for it.
Creates a new phaser with the given number of registered unarrived parties, no parent, and initial phase number 0.
创建指定数量parties的Phaser,初始阶段为0
public Phaser(Phaser parent,int parties)
Creates a new phaser with the given parent and number of registered unarrived parties. When the given parent is non-null and the given number of parties is greater than zero, this child phaser is registered with its parent.
publicclassMyPhaser{ static Random r = new Random(); static MarriagePhase phaser = new MarriagePhase();
publicstaticvoidmain(String[] args){ phaser.bulkRegister(7); for (int i = 0; i < 5; i++) { new Thread(new Person("P"+i)).start(); } new Thread(new Person("新娘")).start(); new Thread(new Person("新郎")).start(); }