1. 程式人生 > >java 併發之CyclicBarrier

java 併發之CyclicBarrier

什麼是CyclicBarrier

可以理解為迴圈柵欄,柵欄就是一種障礙物.假如我們將計數器設定為10,那麼湊齊第一批10個執行緒後,計數器就會歸零,然後接著湊齊下一批10個執行緒,這就是迴圈柵欄的含義.
構造器:

public CyclicBarrier(int parties, Runnable barrierAction) {
      if (parties <= 0) throw new IllegalArgumentException();
      this.parties = parties;
      this.count = parties;
      this
.barrierCommand = barrierAction; }

parties:計數總數,也就是參與的執行緒總數. barrierAction 當計數器一次完成計數後,系統會執行的動作

示例

public class CyclicBarrierDemo {
    public static class Soldier implements Runnable {
        private String soldier;
        private final CyclicBarrier cyclic;

        public Soldier(CyclicBarrier cyclic, String soldier) {
            this
.soldier = soldier; this.cyclic = cyclic; } /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see
Thread#run() */
@Override public void run() { try { //等待所有士兵到齊 cyclic.await(); doWork(); //等待所有士兵完成工作 cyclic.await(); } catch (InterruptedException e) {//在等待過程中,執行緒被中斷 e.printStackTrace(); } catch (BrokenBarrierException e) {//表示當前CyclicBarrier已經損壞.系統無法等到所有執行緒到齊了. e.printStackTrace(); } } void doWork() { try { Thread.sleep(Math.abs(new Random().nextInt() % 10000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(soldier + ":任務完成"); } } public static class BarrierRun implements Runnable { boolean flag; int N; public BarrierRun(boolean flag, int N) { this.flag = flag; this.N = N; } /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { if (flag) { System.out.println("司令:[士兵" + N + "個,任務完成!]"); } else { System.out.println("司令:[士兵" + N + "個,集合完畢!]"); flag = true; } } } public static void main(String[] args) { final int N = 10; Thread[] allSoldier = new Thread[N]; boolean flag = false; CyclicBarrier cyclic = new CyclicBarrier(N, new BarrierRun(flag, N)); //設定屏障點,主要為了執行這個方法 System.out.println("集合隊伍! "); for (int i = 0; i < N; i++) { System.out.println("士兵" + i + "報道! "); allSoldier[i] = new Thread(new Soldier(cyclic, "士兵" + i)); allSoldier[i].start(); } } }

結果
這裡寫圖片描述