Phaser
书上的小例子,用婚礼流程比较形象的演示了phaser的使用。
Phaser 是一个类,继承这个类重写onAdvance(int phase, int registeredParties)
参数:两个参数分别是第几个阶段和到达这个阶段的线程数。
返回值:返回ture表示这个phaser结束了,因此只有最后一个阶段返回ture,其他阶段返回false。
phase.bulkRegister(7);//注册总线程数。
{
static MyPhase phase = new MyPhase();
public static void main(String[] args){
// 参数婚礼的总人数为7
phase.bulkRegister(7);
// 5个参加婚礼的客人
for (int i = 0;i<5;i++){
new Thread(new Person("P"+i)).start();
}
// 新郎和新娘
new Thread(new Person("新郎")).start();
new Thread(new Person("新娘")).start();
}
/**
* 参加婚礼的人,含新郎新娘
*/
static class Person implements Runnable{
private String name;
public Person(String name) {
this.name = name;
}
public void arrived() {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
System.out.printf("%s is arrived! \n",name);
phase.arriveAndAwaitAdvance();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void eat() {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
System.out.printf("%s is eated! \n",name);
phase.arriveAndAwaitAdvance();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void leave() {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
System.out.printf("%s is leave! \n",name);
phase.arriveAndAwaitAdvance();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void xx() {
try {
if(name.equals("新郎")|| name.equals("新娘")) {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
System.out.printf("%s is xx! \n",name);
phase.arriveAndAwaitAdvance();
}else {
// 客人不参与XX 到达这个阶段就直接撤销。
phase.arriveAndDeregister();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// 每个人需要依次执行到达,吃饭,离席,XX(客人就不要参加了)
arrived();
eat();
leave();
xx();
}
}
static class MyPhase extends Phaser{
@Override
protected boolean onAdvance(int phase, int registeredParties) {
switch (phase){
case 0:{
System.out.println("所有人到齐了,人数为:"+registeredParties);
return false;
}
case 1:{
System.out.println("所有人开始吃饭 !!人数为:"+registeredParties);
return false;
}
case 2:{
System.out.println("所有人吃完了,离席!!!人数为:"+registeredParties);
return false;
}
case 3:{
System.out.println("xx的人数为:"+registeredParties);
return true;
}
default:{
return true;
}
}
}
}
}
测试结果为:
P0 is arrived!
P3 is arrived!
新郎 is arrived!
P1 is arrived!
P4 is arrived!
P2 is arrived!
新娘 is arrived!
所有人到齐了,人数为:7
P1 is eated!
P2 is eated!
P0 is eated!
新郎 is eated!
P4 is eated!
新娘 is eated!
P3 is eated!
所有人开始吃饭 !!人数为:7
P2 is leave!
新娘 is leave!
P0 is leave!
P3 is leave!
P1 is leave!
新郎 is leave!
P4 is leave!
所有人吃完了,离席!!!人数为:7
新娘 is xx!
新郎 is xx!
xx的人数为:2