CyclicBarrier默认的构造方法是CyclicBarrier(int parties),parties表示栅栏需要拦截的线程数量。
每个线程调用await方法,计数器减1,减少为0前所有线程都必须等待。
CyclicBarrier还提供一个更高级的构造函数CyclicBarrier(int parties,Runnable barrier-Action),用于在线程到达屏障时,优先执行barrierAction,方便处理更复杂的业务场景
1 import java.util.concurrent.BrokenBarrierException; 2 import java.util.concurrent.CyclicBarrier; 3 4 /** 5 * 6 * @author sulishi 7 * @version 1.0 8 * @date 2021/1/31 9 */ 10 public class CyclicBarrierTest2 { 11 static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new FirstRun()); 12 13 public static void main(String[] args) throws BrokenBarrierException, InterruptedException { 14 //线程A输出1 15 new Thread(new Runnable() { 16 @Override 17 public void run() { 18 try { 19 cyclicBarrier.await(); 20 System.out.println(1); 21 } 22 catch (Exception e) { 23 } 24 } 25 }).start(); 26 //主线程输出2 27 cyclicBarrier.await(); 28 System.out.println(2); 29 } 30 31 static class FirstRun implements Runnable { 32 @Override 33 public void run() { 34 System.out.println(3); 35 } 36 } 37 }
输出结果为312 或321,3始终先执行