一 描述
CyclicBarrier初始化时规定一个数目,然后计算调用了CyclicBarrier.await()进入等待的线程数。当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。
CyclicBarrier就象它名字的意思一样,可看成是个障碍, 所有的线程必须到齐后才能一起通过这个障碍。
CyclicBarrier初始时还可带一个Runnable的参数, 此Runnable任务在CyclicBarrier的数目达到后,所有其它线程被唤醒前被执行。
二 代码实例
1 public class CyclicBarrierDemo { 2 3 private static final int THREAD_NUM = 5; 4 5 public static class WorkerThread implements Runnable { 6 7 CyclicBarrier barrier; 8 9 public WorkerThread(CyclicBarrier b) { 10 this.barrier = b; 11 } 12 13 public void run() { 14 try { 15 System.out.println("Worker's waiting"); 16 //线程在这里等待,直到所有线程都到达barrier 17 barrier.await(); 18 System.out.println("ID:" + Thread.currentThread().getId() + " Working"); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 } 23 } 24 25 public static void main(String[] args) { 26 //当所有线程到达barrier时执行 27 CyclicBarrier cb = new CyclicBarrier(THREAD_NUM, () -> System.out.println("Inside Barrier")); 28 29 for (int i = 0; i < THREAD_NUM; i++) { 30 new Thread(new WorkerThread(cb)).start(); 31 } 32 } 33 }
输出结果
Worker's waiting Worker's waiting Worker's waiting Worker's waiting Worker's waiting Inside Barrier ID:13 Working ID:11 Working ID:12 Working ID:10 Working ID:14 Working