咱們有些場景,是須要使用 多線各一塊兒執行某些操做的,好比進行併發測試,好比進行多線程數據彙總。安全
天然,咱們可使用 CountDownLatch, CyclicBarrier, 以及多個 Thread.join()。 雖然最終的效果都差很少,但實際卻各有千秋。咱們此處主要看 CyclicBarrier .多線程
概要: CyclicBarrier 使用 n 個 permit 進行初始化,當n個線程都到達後進行放行,而後進入下一個循環週期。在放行的同時,還能夠設置一個執行方法,即至關於回調操做。併發
主循環等待!app
// CyclicBarrier /** * 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 { // 使用的一 Generation 表明一輩子循環週期,當週期到達後,替換此值 final Generation g = generation; // 針對異常狀況,直接拋出異常,通常是用於多線程之間通訊 if (g.broken) throw new BrokenBarrierException(); if (Thread.interrupted()) { // breakBarrier 是針對其餘線程的,而 拋出的 InterruptedException 是針對當前線程的 // 從而達到中斷標誌全局可見的效果 breakBarrier(); throw new InterruptedException(); } // 如下邏輯爲進入了等待區域, count-1, 當減到0以後,就表明須要進行放行了 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 { // 一直在此處進行等待,直到被喚醒,被喚醒時,則意味着有事件發生了 // 等待中將會釋放鎖,從而讓其餘線程進入 // 此處的 await() 是一個複雜的故事,由於它要保證在 notify 時的鎖競爭問題 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(); } }
能夠看到,主要邏輯就是在於 生命週期的迭代操做,可是這個生命週期的標誌異常的簡單:less
// 只有一個標識位, broken 爲 true 時,發生了異常,總體退出 private static class Generation { boolean broken = false; }
而到達的線程數足夠以後,須要進行週期迭代,只是 Generation 更換一個變量,另外就是要起到通知全部等待線程的做用:ide
// CyclicBarrier /** * Updates state on barrier trip and wakes up everyone. * Called only while holding lock. */ private void nextGeneration() { // signal completion of last generation // 先通知等待線程,但此時當前線程仍然持有鎖,因此其餘線程仍然處理等待狀態 // 而後再設置下一週期,直到本線程當前同步塊退出以後,其餘線程才能夠進行工做 // 此處依賴於 ReentrantLock // 此處體現 wait/notify 的鎖做用域問題 trip.signalAll(); // set up next generation count = parties; generation = new Generation(); }
而調用 入口 僅是調用 dowait() 方法而已.工具
// CyclicBarrier public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { throw new Error(toe); // cannot happen } }
CyclicBarrier 自己的等待邏輯是簡單巧妙的,使用 ReentrantLock 的目的是爲了實現帶超時等待的效果,不然就是一個 wait/notify 機制的實現。固然 wait/notify 的邏輯仍是很關鍵很複雜的,後續若有必要再寫一文說明。oop
完整代碼以下:測試
public class CyclicBarrier { /** * 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(); } } /** * Creates a new {@code CyclicBarrier} that will trip when the * given number of parties (threads) are waiting upon it, and which * will execute the given barrier action when the barrier is tripped, * performed by the last thread entering the barrier. * * @param parties the number of threads that must invoke {@link #await} * before the barrier is tripped * @param barrierAction the command to execute when the barrier is * tripped, or {@code null} if there is no action * @throws IllegalArgumentException if {@code parties} is less than 1 */ public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; } /** * Creates a new {@code CyclicBarrier} that will trip when the * given number of parties (threads) are waiting upon it, and * does not perform a predefined action when the barrier is tripped. * * @param parties the number of threads that must invoke {@link #await} * before the barrier is tripped * @throws IllegalArgumentException if {@code parties} is less than 1 */ public CyclicBarrier(int parties) { this(parties, null); } /** * Returns the number of parties required to trip this barrier. * * @return the number of parties required to trip this barrier */ public int getParties() { return parties; } /** * Waits until all {@linkplain #getParties parties} have invoked * {@code await} on this barrier. * * <p>If the current thread is not the last to arrive then it is * disabled for thread scheduling purposes and lies dormant until * one of the following things happens: * <ul> * <li>The last thread arrives; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * one of the other waiting threads; or * <li>Some other thread times out while waiting for barrier; or * <li>Some other thread invokes {@link #reset} on this barrier. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when * {@code await} is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting, * then all other waiting threads will throw * {@link BrokenBarrierException} and the barrier is placed in the broken * state. * * <p>If the current thread is the last thread to arrive, and a * non-null barrier action was supplied in the constructor, then the * current thread runs the action before allowing the other threads to * continue. * If an exception occurs during the barrier action then that exception * will be propagated in the current thread and the barrier is placed in * the broken state. * * @return the arrival index of the current thread, where index * {@code getParties() - 1} indicates the first * to arrive and zero indicates the last to arrive * @throws InterruptedException if the current thread was interrupted * while waiting * @throws BrokenBarrierException if <em>another</em> thread was * interrupted or timed out while the current thread was * waiting, or the barrier was reset, or the barrier was * broken when {@code await} was called, or the barrier * action (if present) failed due to an exception */ public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { throw new Error(toe); // cannot happen } } /** * Waits until all {@linkplain #getParties parties} have invoked * {@code await} on this barrier, or the specified waiting time elapses. * * <p>If the current thread is not the last to arrive then it is * disabled for thread scheduling purposes and lies dormant until * one of the following things happens: * <ul> * <li>The last thread arrives; or * <li>The specified timeout elapses; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * one of the other waiting threads; or * <li>Some other thread times out while waiting for barrier; or * <li>Some other thread invokes {@link #reset} on this barrier. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then {@link TimeoutException} * is thrown. If the time is less than or equal to zero, the * method will not wait at all. * * <p>If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when * {@code await} is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * * <p>If any thread is {@linkplain Thread#interrupt interrupted} while * waiting, then all other waiting threads will throw {@link * BrokenBarrierException} and the barrier is placed in the broken * state. * * <p>If the current thread is the last thread to arrive, and a * non-null barrier action was supplied in the constructor, then the * current thread runs the action before allowing the other threads to * continue. * If an exception occurs during the barrier action then that exception * will be propagated in the current thread and the barrier is placed in * the broken state. * * @param timeout the time to wait for the barrier * @param unit the time unit of the timeout parameter * @return the arrival index of the current thread, where index * {@code getParties() - 1} indicates the first * to arrive and zero indicates the last to arrive * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the specified timeout elapses. * In this case the barrier will be broken. * @throws BrokenBarrierException if <em>another</em> thread was * interrupted or timed out while the current thread was * waiting, or the barrier was reset, or the barrier was broken * when {@code await} was called, or the barrier action (if * present) failed due to an exception */ public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException { return dowait(true, unit.toNanos(timeout)); } /** * Queries if this barrier is in a broken state. * * @return {@code true} if one or more parties broke out of this * barrier due to interruption or timeout since * construction or the last reset, or a barrier action * failed due to an exception; {@code false} otherwise. */ public boolean isBroken() { final ReentrantLock lock = this.lock; lock.lock(); try { return generation.broken; } finally { lock.unlock(); } } /** * Resets the barrier to its initial state. If any parties are * currently waiting at the barrier, they will return with a * {@link BrokenBarrierException}. Note that resets <em>after</em> * a breakage has occurred for other reasons can be complicated to * carry out; threads need to re-synchronize in some other way, * and choose one to perform the reset. It may be preferable to * instead create a new barrier for subsequent use. */ public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); // break the current generation nextGeneration(); // start a new generation } finally { lock.unlock(); } } /** * Returns the number of parties currently waiting at the barrier. * This method is primarily useful for debugging and assertions. * * @return the number of parties currently blocked in {@link #await} */ public int getNumberWaiting() { final ReentrantLock lock = this.lock; lock.lock(); try { return parties - count; } finally { lock.unlock(); } } }
CountDownLatch 會在初始化時,申請 n 個 permit, 調用 await() 進行阻塞, 直到 permit=0 時,await() 才進行返回。每調用一次 countDown(); permit 都會減1直到爲0止;ui
// CountDownLatch.await() 等待 public void await() throws InterruptedException { // 僅是去嘗試獲取一個而已 sync.acquireSharedInterruptibly(1); } // CountDownLatch.countDown() 釋放鎖, 當 permit=0 後,放行 await() public void countDown() { // 此處僅是委託給了 AQS 進行釋放、通知處理 sync.releaseShared(1); } // CountDownLatch 內部鎖實現的是否能夠持有鎖的邏輯 /** * Synchronization control For CountDownLatch. * Uses AQS state to represent count. */ private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; Sync(int count) { setState(count); } int getCount() { return getState(); } protected int tryAcquireShared(int acquires) { // 只要 state=0, 均可以放行 return (getState() == 0) ? 1 : -1; } // 釋放鎖 countDown 邏輯, 作減1操做 protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); // 若是已經被釋放,則直接返回 if (c == 0) return false; // 忽略傳入值 releases, 只作減1操做, 因此 state 一定有等於0的時候 int nextc = c-1; if (compareAndSetState(c, nextc)) // 只有等於0, 才能進行真正的釋放通知操做 return nextc == 0; } } }
能夠看出, CountDownLatch 的同時等待實現更加簡單,幾乎都是依賴於 AQS 進行實現。一樣,從實際效果來講,也是一個 wait/notify 的實現。只是此處的 notify 執行完以後就釋放了鎖,即沒法保證 notify 以後的線程安全性。
上面兩個工具也都是AQS實現的,由此也可知AQS的重要性!
嘮叨: 論 wait/notify 機制的安全性!