并發(fā)工具類之(CountDownLatch,CyclicBarrier)

CountDownLatch

可以理解為線程的計(jì)數(shù)器骂维,使一個(gè)線程等待一組線程執(zhí)行完以后在執(zhí)行惹资,初始值為線程數(shù)的值,當(dāng)一個(gè)線程執(zhí)行完以后航闺,計(jì)數(shù)器的值減1褪测,當(dāng)計(jì)數(shù)器為0時(shí),表示計(jì)數(shù)器上所有線程數(shù)執(zhí)行完成潦刃,開始執(zhí)行后續(xù)的任務(wù)侮措。且不支持計(jì)數(shù)器重置,當(dāng)計(jì)數(shù)器為0后乖杠,當(dāng)其他線程調(diào)await時(shí)分扎,會(huì)直接通過。

先寫個(gè)簡(jiǎn)單的例子:

@Override
    public void run(ApplicationArguments args) throws Exception{

        //創(chuàng)建固定線程數(shù)胧洒,來測(cè)試計(jì)數(shù)器的使用
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        //初始化計(jì)數(shù)器
        CountDownLatch countDownLatch = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info("runnable start--> Threadname:{}",Thread.currentThread().getName());

                        Thread.sleep(1000);

                        log.info("runnable end--> Threadname:{}",Thread.currentThread().getName());
                        countDownLatch.countDown();//線程執(zhí)行完減1
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            executorService.execute(runnable);
        }

        log.info("main --> 等待子線程執(zhí)行完N废拧!卫漫!");
        //獲取計(jì)數(shù)器值
        log.info("current count -->{}",countDownLatch.getCount());

        //阻塞菲饼,等待計(jì)數(shù)器執(zhí)行完

        //如果設(shè)置了超時(shí)時(shí)間,到時(shí)間會(huì)直接走下面的線程
        //countDownLatch.await(100, TimeUnit.MILLISECONDS);

        countDownLatch.await();

        log.info("main 開始執(zhí)行汛兜。巴粪。。");
        log.info("current count -->{}",countDownLatch.getCount());
    }

執(zhí)行結(jié)果:

2019-12-05 20:14:31.302  INFO 1160 --- [pool-1-thread-5] com.laod.MemcachedApplication            : runnable start--> Threadname:pool-1-thread-5
2019-12-05 20:14:31.301  INFO 1160 --- [pool-1-thread-3] com.laod.MemcachedApplication            : runnable start--> Threadname:pool-1-thread-3
2019-12-05 20:14:31.301  INFO 1160 --- [pool-1-thread-4] com.laod.MemcachedApplication            : runnable start--> Threadname:pool-1-thread-4
2019-12-05 20:14:31.302  INFO 1160 --- [           main] com.laod.MemcachedApplication            : main --> 等待子線程執(zhí)行完!8馗辫塌!
2019-12-05 20:14:31.300  INFO 1160 --- [pool-1-thread-1] com.laod.MemcachedApplication            : runnable start--> Threadname:pool-1-thread-1
2019-12-05 20:14:31.300  INFO 1160 --- [pool-1-thread-2] com.laod.MemcachedApplication            : runnable start--> Threadname:pool-1-thread-2
2019-12-05 20:14:31.302  INFO 1160 --- [           main] com.laod.MemcachedApplication            : current count -->5
2019-12-05 20:14:32.306  INFO 1160 --- [pool-1-thread-5] com.laod.MemcachedApplication            : runnable end--> Threadname:pool-1-thread-5
2019-12-05 20:14:32.306  INFO 1160 --- [pool-1-thread-2] com.laod.MemcachedApplication            : runnable end--> Threadname:pool-1-thread-2
2019-12-05 20:14:32.306  INFO 1160 --- [pool-1-thread-4] com.laod.MemcachedApplication            : runnable end--> Threadname:pool-1-thread-4
2019-12-05 20:14:32.306  INFO 1160 --- [pool-1-thread-1] com.laod.MemcachedApplication            : runnable end--> Threadname:pool-1-thread-1
2019-12-05 20:14:32.306  INFO 1160 --- [pool-1-thread-3] com.laod.MemcachedApplication            : runnable end--> Threadname:pool-1-thread-3
2019-12-05 20:14:32.307  INFO 1160 --- [           main] com.laod.MemcachedApplication            : main 開始執(zhí)行。派哲。臼氨。
2019-12-05 20:14:32.307  INFO 1160 --- [           main] com.laod.MemcachedApplication            : current count -->0

CyclicBarrier

上面的CountDownLatch,如果業(yè)務(wù)需兩個(gè)線程步調(diào)一致芭届,然后在通知其他線程储矩,雖然CountDownLatch也可以做,定義計(jì)數(shù)器2褂乍,每個(gè)線程執(zhí)行完后都減1持隧,如果計(jì)數(shù)器大于0,就線程1或者線程2等待逃片,如果計(jì)數(shù)器等于0屡拨,就喚醒線程1,線程2褥实,在執(zhí)行其他線程呀狼。

雖然這樣也可以實(shí)現(xiàn),兩線程步調(diào)一致损离,但是較繁瑣哥艇,Java并發(fā)包內(nèi)有現(xiàn)成的可以使用:CyclicBarrier,與上面很打一個(gè)區(qū)別僻澎,這個(gè)有自動(dòng)重置貌踏,回調(diào)方法的功能,當(dāng)減到 0 的時(shí)候窟勃,會(huì)自動(dòng)重置你設(shè)置的初始值哩俭,循環(huán)執(zhí)行 直接上例子:

@Override
    public void run(ApplicationArguments args) throws Exception{

        // 業(yè)務(wù)1
        Vector<String> pos = new Vector<String>();
        // 業(yè)務(wù)2
        Vector<String> dos = new Vector<String>();

        //創(chuàng)建固定線程數(shù),來測(cè)試計(jì)數(shù)器的使用
        ExecutorService executor = Executors.newFixedThreadPool(2);

        //從字面意思就能理解 可循環(huán)利用
        CyclicBarrier barrier = new CyclicBarrier(2,() ->{
            executor.execute(()->check(pos,dos));
        });

        //業(yè)務(wù)1
        Thread T1 = new Thread(()->{
            while (1==1){
                //處理具體的業(yè)務(wù)
                try {
                    log.info("模擬業(yè)務(wù)1一直有數(shù)據(jù)");

                    pos.add("1");
                    barrier.await();

                    log.info("numberwaiting -->{}",barrier.getNumberWaiting());

                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        T1.start();

        //業(yè)務(wù)2
        Thread T2 = new Thread(()->{

            while (1==1){
                //處理具體的業(yè)務(wù)
                try {
                    log.info("模擬業(yè)務(wù)2一直有數(shù)據(jù)");

                    dos.add("2");
                    barrier.await();

                    log.info("numberwaiting -->{}",barrier.getNumberWaiting());

                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }

        });
        T2.start();
        log.debug("-----");
    }

    private void check(Vector<String> pos, Vector<String> dos) {

        pos.remove(0);
        dos.remove(0);

        log.info("--- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致");
    }

執(zhí)行結(jié)果如下拳恋,可以很清楚看到兩線程業(yè)務(wù)處理完成后,在做其他處理:

2019-12-06 09:28:02.067  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:02.067  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:02.068  INFO 1698 --- [pool-1-thread-1] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:02.068  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:02.068  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:02.071  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:03.071  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:03.072  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:03.072  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:03.074  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:03.075  INFO 1698 --- [pool-1-thread-2] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:04.077  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:04.077  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:04.077  INFO 1698 --- [pool-1-thread-1] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:04.077  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:04.079  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:05.083  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:05.084  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:05.084  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:05.084  INFO 1698 --- [pool-1-thread-2] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:05.085  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:06.089  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:06.089  INFO 1698 --- [pool-1-thread-1] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:06.089  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:06.089  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:06.091  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:07.091  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:07.091  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:07.091  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:07.091  INFO 1698 --- [pool-1-thread-2] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:07.092  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)
2019-12-06 09:28:08.096  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)1一直有數(shù)據(jù)
2019-12-06 09:28:08.096  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:08.096  INFO 1698 --- [       Thread-9] com.laod.MemcachedApplication            : numberwaiting -->0
2019-12-06 09:28:08.096  INFO 1698 --- [pool-1-thread-1] com.laod.MemcachedApplication            : --- 處理業(yè)務(wù)場(chǎng)景 步調(diào)一致
2019-12-06 09:28:08.098  INFO 1698 --- [      Thread-10] com.laod.MemcachedApplication            : 模擬業(yè)務(wù)2一直有數(shù)據(jù)

總結(jié):

CountDownLatch:
業(yè)務(wù)場(chǎng)景:一個(gè)線程等待多個(gè)線程的執(zhí)行場(chǎng)景砸捏,不能循環(huán)利用谬运,一旦計(jì)數(shù)器為0后,且有線程調(diào)用await()垦藏,會(huì)直接通過梆暖。
CyclicBarrier:
業(yè)務(wù)場(chǎng)景:一組線程之間相互等待,可循環(huán)利用掂骏,計(jì)數(shù)器為0后轰驳,會(huì)自動(dòng)重置,而且還支持回調(diào)函數(shù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末级解,一起剝皮案震驚了整個(gè)濱河市冒黑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌勤哗,老刑警劉巖抡爹,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異芒划,居然都是意外死亡冬竟,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門民逼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泵殴,“玉大人,你說我怎么就攤上這事拼苍⌒ψ纾” “怎么了?”我有些...
    開封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵映屋,是天一觀的道長(zhǎng)苟鸯。 經(jīng)常有香客問我,道長(zhǎng)棚点,這世上最難降的妖魔是什么早处? 我笑而不...
    開封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮瘫析,結(jié)果婚禮上砌梆,老公的妹妹穿的比我還像新娘。我一直安慰自己贬循,他們只是感情好咸包,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著杖虾,像睡著了一般烂瘫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上奇适,一...
    開封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天坟比,我揣著相機(jī)與錄音,去河邊找鬼嚷往。 笑死葛账,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的皮仁。 我是一名探鬼主播籍琳,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼菲宴,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了趋急?” 一聲冷哼從身側(cè)響起喝峦,我...
    開封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宣谈,沒想到半個(gè)月后愈犹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡闻丑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年漩怎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嗦嗡。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡勋锤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出侥祭,到底是詐尸還是另有隱情叁执,我是刑警寧澤,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布矮冬,位于F島的核電站谈宛,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏胎署。R本人自食惡果不足惜吆录,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望琼牧。 院中可真熱鬧恢筝,春花似錦、人聲如沸巨坊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽趾撵。三九已至侄柔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間占调,已是汗流浹背勋拟。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留妈候,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓挂滓,卻偏偏與公主長(zhǎng)得像苦银,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351