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:true
3、例子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:-2147483645
4、例子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
- 现状|程序员现状揭秘:平均年薪20.36万,Java人才需求量最大
- Store|苹果将在韩国开设第二家Apple Store直营店 并发布纪念壁
- Linux(服务器编程):百万并发服务器系统参数调优
- 程序员学英语第1天——JavaScript 程序测试的介绍1
- 三年Java开发,刚从美团、京东、阿里面试归来,分享个人面经
- 《深入理解Java虚拟机》:对象创建、布局和访问全过程
- 菜鸟学编程,不懂C++ this指针?还不赶快来学一学
- java面试题整理
- Kotlin集合vs Kotlin序列与Java流
- 编程猫领衔,9家编程app测评一览详解