CyclicBarrier-循环栅栏线程到达栅栏时调用await方法被阻塞,只有线程数据达到栅栏设置的阈值时,栅栏放行,所有线程继续执行,此轮结束,栅栏进入下一轮。案例:3个线程等待栅栏放行Task

import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;public class Task implements Runnable{ private CyclicBarrier cyclicBarrier; public Task(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "准备就绪"); cyclicBarrier.await(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + "中断了......"); } catch (BrokenBarrierException e) { System.out.println(Thread.currentThread().getName() + "抛出损坏异常...."); } }}启动文件

import java.util.concurrent.CyclicBarrier;public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("主线程开始......"); CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){ @Override public void run() { System.out.println("子线程全部就位,开始执行制定任务......"); } }); Thread t1 = new Thread(new Task(cb), "Thread-1"); Thread t2 = new Thread(new Task(cb), "Thread-2"); Thread t3 = new Thread(new Task(cb), "Thread-3"); t1.start(); t2.start(); t3.start(); Thread.sleep(2000); System.out.println("主线程执行完毕"); }}结果:

CyclicBarrier的异常CyclicBarrier如果不能满足阈值,超时或者等待的线程被中断了,则所有等待线程都会抛出损坏异常,然后进入下一轮。

案例:损坏异常,假设阈值为4,已经有3个线程等待,其中一个中断。Task代码不变启动文件修改

import java.util.concurrent.CyclicBarrier;public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("主线程开始......"); CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){ @Override public void run() { System.out.println("子线程全部就位,开始执行制定任务......"); } }); Thread t1 = new Thread(new Task(cb), "Thread-1"); Thread t2 = new Thread(new Task(cb), "Thread-2"); Thread t3 = new Thread(new Task(cb), "Thread-3"); t1.start(); t2.start(); t3.start(); Thread.sleep(1000); t1.interrupt(); Thread.sleep(2000); System.out.println("主线程执行完毕"); }}结果:

源码分析:CyclicBarrier基于ReentrantLock和Condition实现锁机制。

成员变量

await方法:



breakBarrier损坏方法: