日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

J.U.C系列(一)CountDownLatch的使用

發(fā)布時間:2025/3/19 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 J.U.C系列(一)CountDownLatch的使用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

CountDownLatch

它是用來控制一個或者多個線程等待多個線程。
它的實現(xiàn)原理是內(nèi)部使用了一個ctn的計數(shù)器,當(dāng)調(diào)用countDown()方法的時候計數(shù)器就執(zhí)行減1操作直到減到0的的時候那些之前調(diào)用await()方法而在等待的線程就會被喚醒。

有一個場景可以很好理解這個關(guān)鍵字的使用:火箭發(fā)射案例。火箭發(fā)射的時候需要每個子程序都準(zhǔn)備好才能發(fā)射,如何做到讓各個子程序異步的去執(zhí)行自己的程序然后都準(zhǔn)備完成再發(fā)射火箭呢?
demo如下

package com.leo.demo.threadtest.countdownlatch;import java.util.concurrent.*;/*** @ClassName: RocketLatchingTest* @Description: 火箭發(fā)射的案例* 1、管理發(fā)射的主程序需要等待各個檢查子程序完成才能發(fā)射* @Author: leo825* @Date: 2019-08-21 10:10* @Version: 1.0*/ public class RocketLatchingTest {public static void main(String[] args) throws InterruptedException {//子線程阻塞CountDownLatch childPro = new CountDownLatch(5);//生成隨機數(shù)模擬子程序執(zhí)行消耗時間ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();//模擬火箭發(fā)射子程序的線程池ExecutorService executor = Executors.newFixedThreadPool(5);for (int i = 0; i < 5; i++) {//模擬一個隨機代表每一個子程序的耗時int costTime = threadLocalRandom.nextInt(10);executor.submit(() -> {try {String threadName = Thread.currentThread().getName();System.out.println(threadName + " 開始處理子程序...");System.out.println(threadName + " 處理時間為:" + costTime + "s");TimeUnit.SECONDS.sleep(costTime);System.out.println(Thread.currentThread().getName() + " 準(zhǔn)備就緒!!!");childPro.countDown();//完成預(yù)期工作并發(fā)出完成信號} catch (Exception e) {e.printStackTrace();}});}System.out.println("發(fā)射程序開始準(zhǔn)備...");childPro.await();//模擬火箭發(fā)射倒計時for (int i = 10; i > 0; i--) {System.out.println("發(fā)射倒計時:" + i);TimeUnit.SECONDS.sleep(1);}System.out.println("點火!!!");executor.shutdown();} }

運行結(jié)果如下:

發(fā)射程序開始準(zhǔn)備... pool-1-thread-1 開始處理子程序... pool-1-thread-1 處理時間為:8s pool-1-thread-2 開始處理子程序... pool-1-thread-2 處理時間為:9s pool-1-thread-5 開始處理子程序... pool-1-thread-4 開始處理子程序... pool-1-thread-3 開始處理子程序... pool-1-thread-4 處理時間為:8s pool-1-thread-5 處理時間為:2s pool-1-thread-3 處理時間為:7s pool-1-thread-5 準(zhǔn)備就緒!!! pool-1-thread-3 準(zhǔn)備就緒!!! pool-1-thread-1 準(zhǔn)備就緒!!! pool-1-thread-4 準(zhǔn)備就緒!!! pool-1-thread-2 準(zhǔn)備就緒!!! 發(fā)射倒計時:10 發(fā)射倒計時:9 發(fā)射倒計時:8 發(fā)射倒計時:7 發(fā)射倒計時:6 發(fā)射倒計時:5 發(fā)射倒計時:4 發(fā)射倒計時:3 發(fā)射倒計時:2 發(fā)射倒計時:1 點火!!!

總結(jié)

以上是生活随笔為你收集整理的J.U.C系列(一)CountDownLatch的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。