java線程并發(fā)countdownlatch類使用示例
package com.yao;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* CountDownLatch是個(gè)計(jì)數(shù)器,它有一個(gè)初始數(shù),
* 等待這個(gè)計(jì)數(shù)器的線程必須等到計(jì)數(shù)器倒數(shù)到零時(shí)才可繼續(xù)。
*/
public class CountDownLatchTest {
/**
* 初始化組件的線程
*/
public static class ComponentThread implements Runnable {
// 計(jì)數(shù)器
CountDownLatch latch;
// 組件ID
int ID;
// 構(gòu)造方法
public ComponentThread(CountDownLatch latch, int ID) {
this.latch = latch;
this.ID = ID;
}
public void run() {
// 初始化組件
System.out.println("Initializing component " + ID);
try {
Thread.sleep(500 * ID);
} catch (InterruptedException e) {
}
System.out.println("Component " + ID + " initialized!");
//將計(jì)數(shù)器減一
latch.countDown();
}
}
/**
* 啟動(dòng)服務(wù)器
*/
public static void startServer() throws Exception {
System.out.println("Server is starting.");
//初始化一個(gè)初始值為3的CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
//起3個(gè)線程分別去啟動(dòng)3個(gè)組件
ExecutorService service = Executors.newCachedThreadPool();
service.submit(new ComponentThread(latch, 1));
service.submit(new ComponentThread(latch, 2));
service.submit(new ComponentThread(latch, 3));
service.shutdown();
//等待3個(gè)組件的初始化工作都完成
latch.await();
//當(dāng)所需的三個(gè)組件都完成時(shí),Server就可繼續(xù)了
System.out.println("Server is up!");
}
public static void main(String[] args) throws Exception {
CountDownLatchTest.startServer();
}
}
相關(guān)文章
springboot驗(yàn)證碼生成以及驗(yàn)證功能舉例詳解
登錄注冊(cè)是大部分系統(tǒng)需要實(shí)現(xiàn)的基本功能,同時(shí)也會(huì)對(duì)登錄驗(yàn)證增加需求,下面這篇文章主要給大家介紹了關(guān)于springboot驗(yàn)證碼生成以及驗(yàn)證功能的相關(guān)資料,需要的朋友可以參考下2023-04-04Java數(shù)據(jù)結(jié)構(gòu)之鏈表、棧、隊(duì)列、樹的實(shí)現(xiàn)方法示例
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之鏈表、棧、隊(duì)列、樹的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Java數(shù)據(jù)結(jié)構(gòu)中鏈表、棧、隊(duì)列、樹的功能、定義及使用方法,需要的朋友可以參考下2019-03-03如何通過(guò)Kaptcha在Web頁(yè)面生成驗(yàn)證碼
這篇文章主要介紹了如何通過(guò)Kaptcha在Web頁(yè)面生成驗(yàn)證碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10idea64.exe.vmoptions文件如何設(shè)置調(diào)整VM配置文件
這篇文章主要介紹了idea64.exe.vmoptions文件如何設(shè)置調(diào)整VM配置文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04IDEA 中創(chuàng)建并部署 JavaWeb 程序的方法步驟(圖文)
本文主要介紹了IDEA 中創(chuàng)建并部署 JavaWeb 程序的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02解釋為什么Java中“1000==1000”為false而”100==100“為true
在日常編程中,我們經(jīng)常遇到一些看似簡(jiǎn)單卻隱藏著復(fù)雜邏輯的問(wèn)題,這篇文章主要介紹了解釋為什么Java中“1000==1000”為false而”100==100“為true,需要的朋友可以參考下2024-01-01