Java并发编程 - Phaser类的使用( 五 )


Student1 到达考试Student0 到达考试Student3 到达考试Student2 到达考试Student4 到达考试学生准备好了,学生人数:5Student4 做第1题开始...Student3 做第1题开始...Student1 做第1题开始...Student2 做第1题开始...Student0 做第1题开始...Student1 做第1题完成...Student2 做第1题完成...Student4 做第1题完成...Student0 做第1题完成...Student3 做第1题完成...第一题所有学生做完Student4 做第2题开始...Student1 做第2题开始...Student2 做第2题开始...Student3 做第2题开始...Student0 做第2题开始...Student1 做第2题完成...Student3 做第2题完成...Student2 做第2题完成...Student0 做第2题完成...Student4 做第2题完成...第二题所有学生做完Student4 做第3题开始...Student2 做第3题开始...Student3 做第3题开始...Student1 做第3题开始...Student0 做第3题开始...Student4 做第3题完成...Student3 做第3题完成...Student2 做第3题完成...Student1 做第3题完成...Student0 做第3题完成...第三题所有学生做完 , 结束考试Phaser has finished:true3、例子3(最多进行到3个phase就会终止)
private static void test3() {int iterations = 2;final Phaser phaser = new Phaser() {protected boolean onAdvance(int phase, int registeredParties) {return phase >= iterations || registeredParties == 0;}};phaser.register();for (int i=0;i<5;i++) {phaser.register();new Thread() {public void run() {do {System.out.println(Thread.currentThread().getName() + " start.");int phase = phaser.arriveAndAwaitAdvance();System.out.println(Thread.currentThread().getName() + " end. phase:" + phase);} while (!phaser.isTerminated());}}.start();}phaser.arriveAndDeregister(); // deregister self, don't wait}输出结果:
Thread-0 start.Thread-1 start.Thread-3 start.Thread-4 start.Thread-2 start.Thread-4 end. phase:1Thread-0 end. phase:1Thread-3 end. phase:1Thread-1 end. phase:1Thread-1 start.Thread-2 end. phase:1Thread-3 start.Thread-0 start.Thread-4 start.Thread-2 start.Thread-2 end. phase:2Thread-2 start.Thread-1 end. phase:2Thread-1 start.Thread-0 end. phase:2Thread-0 start.Thread-4 end. phase:2Thread-4 start.Thread-3 end. phase:2Thread-3 start.Thread-3 end. phase:3Thread-4 end. phase:-2147483645Thread-0 end. phase:-2147483645Thread-2 end. phase:-2147483645Thread-1 end. phase:-21474836454、例子4(phaser的父子关系)
private static void test4() {final Phaser parent = new Phaser();int phaserParty1 = 5;int phaserParty2 = 4;// 在Phaser的构造函数中,parent 将会调用doRegister进行注册(phase = parent.doRegister(1))final Phaser phaser1 = new Phaser(parent,phaserParty1);final Phaser phaser2 = new Phaser(parent,phaserParty2);System.out.println("tasks start");for(int i = 0;i输出结果:
tasks startThreadA-2, index:2ThreadA-1, index:1ThreadA-4, index:4ThreadA-3, index:3wait for all tasks to be finished. phase:0, RegisteredParties:2ThreadA-0, index:0ThreadB-2, index:2ThreadB-3, index:3ThreadB-0, index:0ThreadB-1, index:1tasks done. phase:1-----------------------------------------------------------
转载自:
;wfr=spider&for=pc