package concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* CountDownLatch倒計(jì)時(shí)鎖
* 阻塞主線程,等子線程全部執(zhí)行完之后主線程繼續(xù)執(zhí)行
*
*/
public class CountDownLatchDemo {
public static int count = 0;
/**
* 計(jì)算1至10000的和
* @param args
*/
public static void main(String[] args) throws InterruptedException {
//定義一個(gè)緩沖線程池
ExecutorService executorService = Executors.newCachedThreadPool();
//定義一個(gè)倒計(jì)時(shí)鎖
CountDownLatch countDownLatch = new CountDownLatch(10000);
for (int i=1;i<=10000;i++){
final int index = i;
//多個(gè)線程執(zhí)行
executorService.execute(()->{
synchronized (CountDownLatchDemo.class){
try {
count += index;
} catch (Exception e) {
e.printStackTrace();
} finally {
//計(jì)數(shù)器減1
countDownLatch.countDown();
}
}
});
}
//線程阻塞,知道countDownLatch計(jì)數(shù)值=0
countDownLatch.await();
System.out.println(count);
//關(guān)閉線程池
executorService.shutdown();
}
}
輸出結(jié)果:50005000
創(chuàng)新互聯(lián)建站主要從事成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)翼城,十余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專(zhuān)業(yè),歡迎來(lái)電咨詢建站服務(wù):13518219792