import java.util.concurrent.Phaser;
/**
* Created by zyBourn on 15/12/25.
*/
public class Entity {
/**
* 工作方式与CyclicBarrier类似,但是可以定义多个阶段
* Phaser()/Phaser(int num):使用指定0/num个party创建Phaser
* register():注册party
* arriveAndAdvance():到达时等待到所有party到达
* arriveAndDeregister():到达时注销想成自己
*/
public static void main(String[] args) {
Phaser phaser=new Phaser(1);
new Worker(phaser,"厨师").start();
new Worker(phaser,"服务员").start();
new Worker(phaser,"传菜员").start();
for (int i=1;i<=3;i++){
phaser.arriveAndAwaitAdvance();
System.out.println("订单"+i+"完成!");
}
phaser.arriveAndDeregister();
System.out.println("处理完成");
}
}
class Worker extends Thread{
private Phaser phaser;
public Worker(Phaser phaser,String name){
setName(name);
this.phaser=phaser;
phaser.register();
}
public void run(){
for (int i = 0; i <=3; i++) {
System.out.println("当前的订单是:"+i+":"+getName());
if (i==3){
phaser.arriveAndDeregister();
}else {
phaser.arriveAndAwaitAdvance();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Phaser 工作方式与CyclicBarrier类似,但是可以定义多个阶段
点赞
收藏