JDK 1.7 添加了 Phaser 分阶段栅栏 有点像多个 CyclicBarrier 组合起来一起使用
话不多收,上代码;
学习自马士兵老师的课
public class Phaser02 {static Random r=new Random();static Phaser phaser=new MarryPhaser();public static void millSleep(int num){try {Thread.sleep(num);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(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();}static class Person implements Runnable{String name;public Person(String name) {this.name = name;}public void arrive(){millSleep(r.nextInt(1000));System.out.println(String.format("%s 到达现场!\n",name));phaser.arriveAndAwaitAdvance();}public void eat(){millSleep(r.nextInt(1000));System.out.println(String.format("%s 吃完!\n",name));phaser.arriveAndAwaitAdvance();}public void leave(){millSleep(r.nextInt(1000));System.out.println(String.format("%s 离开!\n",name));phaser.arriveAndAwaitAdvance();}public void hug(){if(name.equalsIgnoreCase("新郎")||name.equalsIgnoreCase("新娘")){millSleep(r.nextInt(1000));System.out.println(String.format("%s 洞房!\n",name));// 到达后继续phaser.arriveAndAwaitAdvance();}else {// 到达后注销phaser.arriveAndDeregister();}}@Overridepublic void run() {arrive();eat();leave();hug();}}
}class MarryPhaser extends Phaser{// 该方法在栅栏被推倒的时候自动调用// 参数1 当前是第几个阶段// 参数2 有多少线程参与这个阶段@Overrideprotected boolean onAdvance(int phase, int registeredParties) {switch (phase){case 0:System.out.println("所有人都到齐了!"+registeredParties);System.out.println();return false;case 1:System.out.println("所有人都吃完了!"+registeredParties);System.out.println();return false;case 2:System.out.println("所有人都离开了!"+registeredParties);System.out.println();return false;case 3:System.out.println("婚礼结束,新浪新娘抱抱!"+registeredParties);System.out.println();return true;default:return true;}}
}