java線程并發(fā)countdownlatch類使用示例
package com.yao;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* CountDownLatch是個計數(shù)器,它有一個初始數(shù),
* 等待這個計數(shù)器的線程必須等到計數(shù)器倒數(shù)到零時才可繼續(xù)。
*/
public class CountDownLatchTest {
/**
* 初始化組件的線程
*/
public static class ComponentThread implements Runnable {
// 計數(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!");
//將計數(shù)器減一
latch.countDown();
}
}
/**
* 啟動服務(wù)器
*/
public static void startServer() throws Exception {
System.out.println("Server is starting.");
//初始化一個初始值為3的CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
//起3個線程分別去啟動3個組件
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個組件的初始化工作都完成
latch.await();
//當(dāng)所需的三個組件都完成時,Server就可繼續(xù)了
System.out.println("Server is up!");
}
public static void main(String[] args) throws Exception {
CountDownLatchTest.startServer();
}
}
相關(guān)文章
基于idea解決springweb項目的Java文件無法執(zhí)行問題
這篇文章給大家介紹了基于idea解決springweb項目的Java文件無法執(zhí)行問題,文中通過圖文結(jié)合的方式給大家介紹的非常詳細(xì),對大家的學(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 的錯誤提示,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
SpringCloud?openfeign聲明式服務(wù)調(diào)用實(shí)現(xiàn)方法介紹
在springcloud中,openfeign是取代了feign作為負(fù)載均衡組件的,feign最早是netflix提供的,他是一個輕量級的支持RESTful的http服務(wù)調(diào)用框架,內(nèi)置了ribbon,而ribbon可以提供負(fù)載均衡機(jī)制,因此feign可以作為一個負(fù)載均衡的遠(yuǎn)程服務(wù)調(diào)用框架使用2022-12-12
解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請求數(shù)據(jù)丟失問題
這篇文章主要介紹了解決在微服務(wù)環(huán)境下遠(yuǎn)程調(diào)用feign和異步線程存在請求數(shù)據(jù)丟失問題,主要包括無異步線程得情況下feign遠(yuǎn)程調(diào)用,異步情況下丟失上下文問題,需要的朋友可以參考下2022-05-05
解決Maven本地倉庫明明有對應(yīng)的jar包但還是報找不到的問題
這篇文章主要介紹了解決Maven本地倉庫明明有對應(yīng)的jar包但還是報找不到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

