個人博客 轉載請註明原創出處。
java.util.concurrent
包裏有幾個能幫助人們管理相互合做的線程集的類,爲多線程常見的應用場景預置了抽象好的類庫。在遇到這些應用場景時應該直接重用合適的庫類而不要試圖提供手工的鎖與條件的集合。java
官方定義上文已經給出,人話版是等待特定數量的線程都到達同步屏障後各線程才繼續執行。多線程
同步屏障有兩個構造函數,第一個構造函數只須要指定須要等待的線程數量,第二構造函數多了一個在特定數量的線程都到達同步屏障時優先執行的Runnable
。app
例子:函數
public class CyclicBarrierTest { // 等待4個線程到達同步屏障,所有到達後優先執行一個 Runnable private static CyclicBarrier cyclicBarrier = new CyclicBarrier(4, () -> System.out.println("所有到達同步屏障" + LocalDateTime.now())); public static void main(String[] args) throws InterruptedException, BrokenBarrierException { Runnable runnable = () -> { System.out.println("到達同步屏障" + LocalDateTime.now()); try { cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out.println("繼續執行"); }; List<Runnable> list = Arrays.asList(runnable, runnable, runnable); list.forEach(runnable1 -> new Thread(runnable1).start()); Thread.sleep(1000); System.out.println("最後一個線程到達同步屏障"); cyclicBarrier.await(); } } 輸出: 到達同步屏障2018-08-12T14:33:16.769 到達同步屏障2018-08-12T14:33:16.769 到達同步屏障2018-08-12T14:33:16.769 最後一個線程到達同步屏障 所有到達同步屏障2018-08-12T14:33:17.746 繼續執行 繼續執行 繼續執行 Process finished with exit code 0
同步屏障的應用場景是那種多線程執行任務,在所有任務執行完成後須要進行一些操做的場景。好比對每一個用戶進行充值統計,最後彙總返回。oop
CyclicBarrier
的方法如上,分別是源碼分析
getParties() 返回須要到達同步屏障的線程數量 await() 等待全部線程到達 await(long, TimeUnit) 帶時間限制的await() isBroken() 判斷阻塞的線程是否被中斷 reset() 重置計數器 getNumberWaiting() 當前被阻塞的線程數量,該方法主要用於調試和斷言
那麼CyclicBarrier
是怎麼實現這個效果的呢?咱們從最經常使用的await()
方法入手。this
能夠看到await()
方法主要是調用了CyclicBarrier
私有的dowait()
方法spa
如註釋所言,dowait()
方法就是實現功能的主要方法了。線程
首先拿到可重入的鎖調試
而後經過內部類Generation
判斷阻塞的線程是否被中斷或該屏障已經失效。
若是線程沒有被中斷,那麼就獲取尚未到達的線程數量並減一。若是已經沒有須要等待的線程了,就判斷是否有須要執行的Runnable
。若是沒報錯就更新屏障狀態並喚醒全部線程繼續執行。Runnable
執行報錯的話執行breakBarrier()
方法。
若是還有未到達的線程,就進入一個死循環,直到超時、線程中斷、屏障失效、所有完成等狀況下退出。
完整的代碼:
/** * Each use of the barrier is represented as a generation instance. * The generation changes whenever the barrier is tripped, or * is reset. There can be many generations associated with threads * using the barrier - due to the non-deterministic way the lock * may be allocated to waiting threads - but only one of these * can be active at a time (the one to which {@code count} applies) * and all the rest are either broken or tripped. * There need not be an active generation if there has been a break * but no subsequent reset. */ private static class Generation { boolean broken = false; } /** The lock for guarding barrier entry */ private final ReentrantLock lock = new ReentrantLock(); /** Condition to wait on until tripped */ private final Condition trip = lock.newCondition(); /** The number of parties */ private final int parties; /* The command to run when tripped */ private final Runnable barrierCommand; /** The current generation */ private Generation generation = new Generation(); /** * Number of parties still waiting. Counts down from parties to 0 * on each generation. It is reset to parties on each new * generation or when broken. */ private int count; /** * Updates state on barrier trip and wakes up everyone. * Called only while holding lock. */ private void nextGeneration() { // signal completion of last generation trip.signalAll(); // set up next generation count = parties; generation = new Generation(); } /** * Sets current barrier generation as broken and wakes up everyone. * Called only while holding lock. */ private void breakBarrier() { generation.broken = true; count = parties; trip.signalAll(); } /** * Main barrier code, covering the various policies. */ 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(); } int index = --count; if (index == 0) { // tripped boolean ranAction = false; try { final Runnable command = barrierCommand; if (command != null) command.run(); ranAction = true; nextGeneration(); return 0; } finally { if (!ranAction) breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out for (;;) { try { if (!timed) trip.await(); else if (nanos > 0L) nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { if (g == generation && ! g.broken) { breakBarrier(); throw ie; } else { // We're about to finish waiting even if we had not // been interrupted, so this interrupt is deemed to // "belong" to subsequent execution. Thread.currentThread().interrupt(); } } if (g.broken) throw new BrokenBarrierException(); if (g != generation) return index; if (timed && nanos <= 0L) { breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); } }