//parties 表示屏障拦截的线程数量
//barrierAction 表示最后一个达到的屏障的线程将执行 barrierAction
public CyclicBarrier(int parties)
public CyclicBarrier(int parties, Runnable barrierAction)
使用示例:
package constxiong.interview;
import java.util.concurrent.CyclicBarrier;
/**
* 测试 CyclicBarrier 的使用
* @author ConstXiong
* @date 2019-12-25 19:22:50
*/
public class TestCyclicBarrier {
public static void main(String[] args) {
int parts = 10;
final CyclicBarrier cb = new CyclicBarrier(parts, () -> {
System.out.println(Thread.currentThread().getName() + ": I'am is last Thread");
});
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ": I'am come");
try {
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": go together");
}).start();
}
}
}
打印结果:
Thread-2: I'am come
Thread-0: I'am come
Thread-1: I'am come
Thread-4: I'am come
Thread-3: I'am come
Thread-6: I'am come
Thread-9: I'am come
Thread-5: I'am come
Thread-7: I'am come
Thread-8: I'am come
Thread-8: I'am is last Thread
Thread-8: go together
Thread-2: go together
Thread-0: go together
Thread-1: go together
Thread-4: go together
Thread-3: go together
Thread-6: go together
Thread-5: go together
Thread-9: go together
Thread-7: go together
CountDownLatch 和 CyclicBarrier 简单比较
ConstXiong 备案号:苏ICP备16009629号-3