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)文章
基于idea解決springweb項(xiàng)目的Java文件無(wú)法執(zhí)行問(wèn)題
這篇文章給大家介紹了基于idea解決springweb項(xiàng)目的Java文件無(wú)法執(zhí)行問(wèn)題,文中通過(guò)圖文結(jié)合的方式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-02-02
Idea 解決 Could not autowire. No beans of ''xxxx'' type found
這篇文章主要介紹了Idea 解決 Could not autowire. No beans of 'xxxx' type found 的錯(cuò)誤提示,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
SpringCloud?openfeign聲明式服務(wù)調(diào)用實(shí)現(xiàn)方法介紹
在springcloud中,openfeign是取代了feign作為負(fù)載均衡組件的,feign最早是netflix提供的,他是一個(gè)輕量級(jí)的支持RESTful的http服務(wù)調(diào)用框架,內(nèi)置了ribbon,而ribbon可以提供負(fù)載均衡機(jī)制,因此feign可以作為一個(gè)負(fù)載均衡的遠(yuǎn)程服務(wù)調(diào)用框架使用2022-12-12
解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請(qǐng)求數(shù)據(jù)丟失問(wèn)題
這篇文章主要介紹了解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請(qǐng)求數(shù)據(jù)丟失問(wèn)題,主要包括無(wú)異步線程得情況下feign遠(yuǎn)程調(diào)用,異步情況下丟失上下文問(wèn)題,需要的朋友可以參考下2022-05-05
解決Maven本地倉(cāng)庫(kù)明明有對(duì)應(yīng)的jar包但還是報(bào)找不到的問(wèn)題
這篇文章主要介紹了解決Maven本地倉(cāng)庫(kù)明明有對(duì)應(yīng)的jar包但還是報(bào)找不到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10

