CyclicBarrier是一個同步輔助類,它容許一組線程相互等待,直到達到某個公共屏障點。而且在釋放等待線程以後,CyclicBarrier是能夠重複使用的。
java
下面這段代碼利用了CyclicBarrier來使得線程建立後相互等待,直到全部的線程都準備好,以此來使多個線程同時執行。app
public class CyclicBarrierTest { public static void main(String[] args) { CyclicBarrierTest cyclicBarrierTest=new CyclicBarrierTest(); cyclicBarrierTest.runThread(); } //有10個線程須要相互等待 CyclicBarrier cyclicBarrier=new CyclicBarrier(10); /** * 建立一個線程 * @return */ private Thread createThread(int i){ Thread thread=new Thread(new Runnable() { @Override public void run() { try { //線程在此相互等待,直到全部線程都準備好 cyclicBarrier.await(); System.out.println("thread"+Thread.currentThread().getName()+"準備完畢"+System.currentTimeMillis()); }catch (InterruptedException e){ e.printStackTrace(); }catch (BrokenBarrierException e){ e.printStackTrace(); } } }); thread.setName("thread-"+i); return thread; } public void runThread(){ ExecutorService executorService= Executors.newFixedThreadPool(10); try { for(int i=0;i<10;i++){ Thread.sleep(100); executorService.submit(createThread(i)); } }catch (InterruptedException e){ e.printStackTrace(); } } }
private static class Generation { //是否被銷燬 boolean broken = false;//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 ,當線程都到待barrier,須要運行的內容*/ private final Runnable barrierCommand; /** The current generation ,記錄當前barrier狀態的對象*/ 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. *當前等待barrier到達的線程的數量 */ private int count;
int await()
方法的具體實現以下:ide
public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { throw new Error(toe); // cannot happen } }
從這個方法能夠看出,實際上起做用的就是dowait(false, 0L);
.
那咱們來看一下dowait(false, 0L);
的具體實現:oop
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(); //若是線程被中斷,就會終止Barrier,喚醒全部的等待線程 throw new InterruptedException(); } //count就是咱們實例化CyclicBarrier時傳入的值 //此時index表明當前是最後幾個等待的線程 int index = --count; if (index == 0) { // tripped //如過當前線程是最後一個等待的線程 //它都已經調用await,說明全部線程都已經到達 //屏障點了,能夠喚醒全部線程了 boolean ranAction = false; try { //若是有barrierCommand,就運行它 final Runnable command = barrierCommand; if (command != null) command.run(); ranAction = true; //更新Barrier狀態,並喚醒全部線程 nextGeneration(); return 0; } finally { if (!ranAction) breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out //自旋等待,直到全部線程都到達屏障點 //或者發生中斷 //或者generation被銷燬 //或者超時 for (;;) { try { if (!timed) trip.await(); //在此利用lock的Condition阻塞,當前線程 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(); //超時就銷燬當前Barrier throw new TimeoutException(); } } } finally { lock.unlock(); } }
在這個方法中,還有幾個比較重要的方法。
用於銷燬Barrier的void breakBarrier()
方法源碼分析
private void breakBarrier() { //將當前gengeration標記爲棄用狀態 generation.broken = true; count = parties;//將等待barrier的線程數量,恢復到以前的值 trip.signalAll(); //喚醒鎖上的Condition上等待的全部線程 }
用於重置CyclicBarrier和喚醒全部等待線程的void nextGeneration()
方法實現以下:this
private void nextGeneration() { // signal completion of last generation trip.signalAll(); //喚醒全部的等待線程 // set up next generation count = parties;//將等待線程數復原,以便CyclicBarrier下次重複使用 generation = new Generation(); //復原generation }
總體看下來,這個CyclicBarrier的實現仍是比較簡單,咱們在實例化CyclicBarrier的時候就指定了一個須要相互等待的線程數。每當一個線程調用await方法的時候,都會去判斷,本身是否是最後一個線程,若是本身是最後一個線程,那麼說明其它線程都在阻塞等待本身,那麼就去喚醒全部等待的線程。若是本身不是最後一個線程,那麼就須要去等待其它的線程,那麼就去自旋,或者阻塞。線程
在整個源碼中比較重要的一點就是CyclicBarrier內部利用了一個ReentrantLock利用它來對代碼塊加鎖,讓線程在它的Condition上阻塞。
每一個CyclicBarrier內部都維護了一個Generation對象,它主要是記錄當前CyclicBarrier的狀態,便是否被棄用。由於CyclicBarrier是能夠重複使用的,所以在全部線程都到達屏障點的時候,會調用nextGeneration()
來重置整個CyclicBarrier,方便下次使用。code
還須要注意的是,CyclicBarrier是會響應中斷,一旦發生中斷,就會重置CyclicBarrier,並喚醒等待的線程。對象