新Java并发线程控制:CyclicBarrier等待所有线程到达一个状态后执行一个线程动作(2)
在附录3的基础上继续深化CyclicBarrier。假设这场龟兔赛跑的过程中,通过CyclicBarrier使得兔子和乌龟均到达400米赛点后,裁判员这时候也需要重启一个秒表计时功能记录当前时间,那么就可以通过CyclicBarrier的构造函数实现一个CyclicBarrier 的“内部线程”做这件事情,例如代码:
private void test() {
int parties = 3;
CyclicBarrier cyclicBarrier = new CyclicBarrier(parties, new Runnable() {
@Override
public void run() {
System.out.println("CyclicBarrier的线程");
}
});
for (int i = 0; i < parties; i++) {
new WorkThread(cyclicBarrier).start();
}
}
private class WorkThread extends Thread {
private CyclicBarrier cyclicBarrier;
public WorkThread(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "开始...");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "结束");
System.out.println(Thread.currentThread().getName() + "等待...");
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + "解锁,go !");
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
2018-10-29 09:59:30.802 3791-3822/zhangphil.test I/System.out: Thread-8开始...
2018-10-29 09:59:30.802 3791-3823/zhangphil.test I/System.out: Thread-9开始...
2018-10-29 09:59:30.802 3791-3821/zhangphil.test I/System.out: Thread-7开始...
2018-10-29 09:59:32.803 3791-3821/zhangphil.test I/System.out: Thread-7结束
2018-10-29 09:59:32.804 3791-3823/zhangphil.test I/System.out: Thread-9结束
2018-10-29 09:59:32.804 3791-3822/zhangphil.test I/System.out: Thread-8结束
2018-10-29 09:59:32.804 3791-3823/zhangphil.test I/System.out: Thread-9等待...
2018-10-29 09:59:32.804 3791-3821/zhangphil.test I/System.out: Thread-7等待...
2018-10-29 09:59:32.804 3791-3822/zhangphil.test I/System.out: Thread-8等待...
2018-10-29 09:59:32.804 3791-3822/zhangphil.test I/System.out: CyclicBarrier的线程
2018-10-29 09:59:32.805 3791-3822/zhangphil.test I/System.out: Thread-8解锁,go !
2018-10-29 09:59:32.805 3791-3823/zhangphil.test I/System.out: Thread-9解锁,go !
2018-10-29 09:59:32.805 3791-3821/zhangphil.test I/System.out: Thread-7解锁,go !