CyclicBarrier如何使用?
- CyclicBarrier 的中文意思是 "循环栅栏",简单理解就是一个可以循环利用的屏障。
- 用于让多个线程阻塞在屏障处,当屏障达到放开的条件,所有被阻塞的线程会继续执行,此时 CyclicBarrier 会自动重置。
- 阻塞线程在屏障处,调用 CyclicBarrier 对象的 await() 方法
- CyclicBarrier 内部主要通过了 ReentrantLock 和 Condition 实现
- CyclicBarrier 有两个构造方法:
//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 简单比较
- CountDownLatch 是一个(或多个)线程等待 N 个线程完成某件事情之后再执行;CyclicBarrier 是每个线程相互等待,即 N 个线程都被拦截之后,然后一起放开执行
- CountDownLatch 无法重置,不可复用;CyclicBarrier 计数到 parts 值时会自动重置,可复用
- Java 自学经历
- Java 面试题 H5
- Java 面试题小程序