Java并發(fā)編程中的CyclicBarrier使用解析
Java的CyclicBarrier
CyclicBarrier從字面意思上來(lái)看,循環(huán)柵欄,這篇文章就來(lái)分析下是到底是如何實(shí)現(xiàn)循環(huán)和柵欄的。
屬性
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(); private int count; private static class Generation { boolean broken = false; } public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; } public CyclicBarrier(int parties) { this(parties, null); }
CyclicBarrier有兩個(gè)構(gòu)造器,一個(gè)接收資源總數(shù),一個(gè)接收資源總數(shù)和回調(diào)線程?;卣{(diào)線程在哪使用,后面再看。
因?yàn)镃yclicBarrier是可以重復(fù)使用的,那么就需要有一個(gè)變量標(biāo)識(shí)所有的線程是屬于同一個(gè)過程的。CyclicBarrier定義了Generation,代際,其中只有一個(gè)變量broken,表示當(dāng)前代際是否被破壞,默認(rèn)為false。
await
CyclicBarrier最重要的方法就是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();//1、獲取鎖 try { final Generation g = generation; //2、是否已更新?lián)Q代 if (g.broken) throw new BrokenBarrierException(); //3、是否被中斷 if (Thread.interrupted()) { //4、跳出柵欄 breakBarrier(); throw new InterruptedException(); } //5、當(dāng)前線程到達(dá)柵欄,計(jì)數(shù)減1 int index = --count; //6、所有線程都到達(dá)了柵欄 if (index == 0) { // tripped boolean ranAction = false; try { //7、獲取回調(diào)線程 final Runnable command = barrierCommand; if (command != null) //8、如果生成時(shí)傳入了回調(diào)線程,啟動(dòng)回調(diào)線程 command.run(); ranAction = true; //9、重置,開始下一代 nextGeneration(); return 0; } finally { //10、如果ranAction為false,說(shuō)明回調(diào)線程執(zhí)行出錯(cuò)了 if (!ranAction) //11、跳出柵欄 breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out for (;;) { try { if (!timed) //12、如果不需要超時(shí)等待,則立即調(diào)用Condition的await trip.await(); else if (nanos > 0L) //13、如果需要超時(shí)等待 nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) {//14、如果等待時(shí)被中斷了 //15、如果等待前和現(xiàn)在處于同一代,并且沒有被跳出過 if (g == generation && ! g.broken) { //16、跳出柵欄 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. //17、不屬于本代的線程,補(bǔ)中斷 Thread.currentThread().interrupt(); } } //18、被其他線程喚醒,此時(shí)本代已經(jīng)被破壞 if (g.broken) throw new BrokenBarrierException(); //19、不屬于本代,又不是因?yàn)閯e的線程中斷 if (g != generation) return index; //20、如果等待超時(shí),跳出柵欄 if (timed && nanos <= 0L) { breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); } } private void breakBarrier() { //1、更新?lián)Q代 generation.broken = true; //2、重置計(jì)數(shù) count = parties; //3、喚醒所有在等待通過柵欄的線程 trip.signalAll(); } private void nextGeneration() { // signal completion of last generation //1、喚醒所有在等待通過柵欄的線程 trip.signalAll(); // set up next generation //2、重置計(jì)數(shù) count = parties; //3、重新生成代際,此時(shí)broken為false generation = new Generation(); }
當(dāng)線程調(diào)用了await時(shí),認(rèn)為該線程已經(jīng)到達(dá)了柵欄,計(jì)數(shù)減1,并進(jìn)入阻塞等待。當(dāng)最后一個(gè)線程到達(dá)柵欄時(shí),如果生成時(shí)傳入了回調(diào)線程,此時(shí)執(zhí)行,然后喚醒所有等待的線程,并更新?lián)Q代。這是正常的流程。
線程在等待時(shí)會(huì)被四種情況喚醒:
- 正常流程,最后一個(gè)線程達(dá)到柵欄后發(fā)起的喚醒
- 本線程在等待時(shí)被中斷了
- 別的線程發(fā)生了中斷,觸發(fā)代際破壞,喚醒了等待中的線程
- 本線程等待超時(shí)了
如果代際被破壞了,會(huì)拋出BrokenBarrierException。
reset
public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); // break the current generation nextGeneration(); // start a new generation } finally { lock.unlock(); } }
線程也可以調(diào)用reset來(lái)重置代際,但是這也會(huì)導(dǎo)致已經(jīng)在等待的線程拋出BrokenBarrierException。
對(duì)比CountDownLatch
CountDownLatch只能使用一次,而CyclicBarrier支持循環(huán)更新代際,多次調(diào)用和重置,同時(shí)它還提供了所有線程到達(dá)柵欄時(shí)執(zhí)行回調(diào)的功能。
CountDownLatch底層是共享獲取,CyclicBarrier是獨(dú)占獲?。ㄍㄟ^調(diào)用ReentrantLock)。
到此這篇關(guān)于Java并發(fā)編程中的CyclicBarrier使用解析的文章就介紹到這了,更多相關(guān)Java的CyclicBarrier內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot集成spring data elasticsearch過程詳解
這篇文章主要介紹了springboot集成spring data elasticsearch過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Spring boot + mybatis + orcale實(shí)現(xiàn)步驟實(shí)例代碼講解
這篇文章主要介紹了Spring boot + mybatis + orcale的實(shí)現(xiàn)步驟實(shí)例代碼講解,需要的朋友可以參考下2017-12-12因不會(huì)遠(yuǎn)程debug調(diào)試我被項(xiàng)目經(jīng)理嘲笑了
這篇文章主要介紹了遠(yuǎn)程debug調(diào)試的相關(guān)內(nèi)容,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08SpringBoot項(xiàng)目使用MDC給日志增加唯一標(biāo)識(shí)的實(shí)現(xiàn)步驟
本文介紹了如何在SpringBoot項(xiàng)目中使用MDC(Mapped?Diagnostic?Context)為日志增加唯一標(biāo)識(shí),以便于日志追蹤,通過創(chuàng)建日志攔截器、配置攔截器以及修改日志配置文件,可以實(shí)現(xiàn)這一功能,文章還提供了源碼地址,方便讀者學(xué)習(xí)和參考,感興趣的朋友一起看看吧2025-03-03springboot 如何通過SpringTemplateEngine渲染html
通過Spring的Thymeleaf模板引擎可以實(shí)現(xiàn)將模板渲染為HTML字符串,而不是直接輸出到瀏覽器,這樣可以對(duì)渲染后的字符串進(jìn)行其他操作,如保存到文件或進(jìn)一步處理,感興趣的朋友跟隨小編一起看看吧2024-10-10Java使用POI從Excel讀取數(shù)據(jù)并存入數(shù)據(jù)庫(kù)(解決讀取到空行問題)
有時(shí)候需要在java中讀取excel文件的內(nèi)容,專業(yè)的方式是使用java POI對(duì)excel進(jìn)行讀取,這篇文章主要給大家介紹了關(guān)于Java使用POI從Excel讀取數(shù)據(jù)并存入數(shù)據(jù)庫(kù),文中介紹的辦法可以解決讀取到空行問題,需要的朋友可以參考下2023-12-12Spring聲明式事務(wù)和@Aspect的攔截順序問題的解決
本篇文章主要介紹了Spring聲明式事務(wù)和@Aspect的攔截順序問題的解決,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-05-05