Java JUC包源碼分析 - 柵欄CyclicBarrier

柵欄不同於倒計時器的一點是倒計時器是一個或N個線程等待其他線程調用countdown()到指定次數後再繼續執行,而柵欄是N個線程之間互相等待,當調用await()到達指定次數後就會喚醒所有等待線程,同時還可以在到達指定數量時觸發一個定製的動作(Runnable,由最後一個調用await()方法並喚醒所有線程的那個線程執行)。另外柵欄是可以循環使用的。

柵欄的實現方式是獨佔鎖+Condition條件來實現的。

先看個Demo:

package com.pzx.test005;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
    static CyclicBarrier cyclicBarrier;

    public static void main(String[] args) {
        cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " do something...");
            }
        });

        ThreadA threadA = new ThreadA();
        for(int i=0; i<5; i++) {
            Thread thread = new Thread(threadA, "t"+i);
            thread.start();
        }
    }

    static class ThreadA implements Runnable{
        @Override
        public void run() {
            System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " begin work...");
            try {
                System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " await...");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

            System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " continue work...");
        }
    }
}

執行結果:

2018-09-11 13:54:27 t0 begin work...
2018-09-11 13:54:27 t0 await...
2018-09-11 13:54:27 t4 begin work...
2018-09-11 13:54:27 t4 await...
2018-09-11 13:54:27 t1 begin work...
2018-09-11 13:54:27 t1 await...
2018-09-11 13:54:27 t3 begin work...
2018-09-11 13:54:27 t3 await...
2018-09-11 13:54:27 t2 begin work...
2018-09-11 13:54:27 t2 await...
2018-09-11 13:54:27 t2 do something...
2018-09-11 13:54:27 t2 continue work...
2018-09-11 13:54:27 t0 continue work...
2018-09-11 13:54:27 t4 continue work...
2018-09-11 13:54:27 t1 continue work...
2018-09-11 13:54:27 t3 continue work...

public class CyclicBarrier {
    // 內部類,因爲柵欄可以循環使用,每使用一次都是一代,這個類可判斷是否處於同一代
    private static class Generation {
        boolean broken = false;
    }
    // 可重入鎖
    private final ReentrantLock lock = new ReentrantLock();
    // 創建Condition,釋放所有線程的條件
    private final Condition trip = lock.newCondition();
    // 柵欄中的線程總個數
    private final int parties;
    // 當要釋放時觸發的動作
    private final Runnable barrierCommand;
    // 創建當前代
    private Generation generation = new Generation();
    // 還剩多少線程可以達到條件,進來一個線程就-1
    private int count;
    // 構造函數
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }
    // 調用await方法阻塞,最後一個線程會喚醒所有線程
    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }

    private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        // 開啓獨佔鎖
        lock.lock();
        try {
            // 獲取當前代數
            final Generation g = generation;
            // 如果當前代的柵欄被破壞了就拋異常
            if (g.broken)
                throw new BrokenBarrierException();
            // 當前線程如果處於中斷狀態就清除中斷標誌,破壞柵欄,拋出被中斷的異常
            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }
            // 一個線程進來後,count-1
            int index = --count;
            // 如果count已經減到0了,說明是時候喚醒所有線程往下運行了
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    // 如果構造函數中有傳入Runnable對象,就在喚醒所有線程之前執行Runnable裏面
                    // 的run方法
                    if (command != null)
                        command.run();
                    ranAction = true;
                    // 重置參數,進入下一代
                    nextGeneration();
                    return 0;
                } finally {
                    // 如果上述喚醒的過程(command.run();)發生了什麼意外導致異常了,就破壞當前 
                    // 的柵欄
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            // 循環,一直到要被喚醒了,或者柵欄被破壞了,或者線程被中斷了,或者超時了
            for (;;) {
                try {
                    // 如果沒有設置超時參數,就執行await(即當前線程阻塞,釋放上面的獨佔鎖,
                    // 等待被喚醒)
                    if (!timed)
                        trip.await();
                    // 如果設置了超時參數,就阻塞超時參數那麼長的時間
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    // 如果發生了中斷異常

                    // 如果還是在當前代並且當前代沒有被破壞
                    if (g == generation && ! g.broken) {
                        // 破壞柵欄,拋出異常
                        breakBarrier();
                        throw ie;
                    } else {
                        // 發生中斷
                        Thread.currentThread().interrupt();
                    }
                }
                // 如果當前代被破壞了,就拋出異常
                if (g.broken)
                    throw new BrokenBarrierException();
                // 如果在這個執行過程中換代了就返回index(即當前count-1值)
                if (g != generation)
                    return index;
                // 輸入的超時參數的合法性判斷,不合法就破壞當前代的柵欄
                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }
  
    // 開啓下一代
    private void nextGeneration() {
        // 喚醒所有的等待的線程,相當於把柵欄拉開
        trip.signalAll();
        // 重置count和generation 
        count = parties;
        generation = new Generation();
    }
    // 破壞柵欄
    private void breakBarrier() {
        // 當前代被破壞置true,重置count,喚醒所有的線程
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }
    // 重置柵欄
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章