您好,登錄后才能下訂單哦!
package concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* CountDownLatch倒計時鎖
* 阻塞主線程,等子線程全部執行完之后主線程繼續執行
*
*/
public class CountDownLatchDemo {
public static int count = 0;
/**
* 計算1至10000的和
* @param args
*/
public static void main(String[] args) throws InterruptedException {
//定義一個緩沖線程池
ExecutorService executorService = Executors.newCachedThreadPool();
//定義一個倒計時鎖
CountDownLatch countDownLatch = new CountDownLatch(10000);
for (int i=1;i<=10000;i++){
final int index = i;
//多個線程執行
executorService.execute(()->{
synchronized (CountDownLatchDemo.class){
try {
count += index;
} catch (Exception e) {
e.printStackTrace();
} finally {
//計數器減1
countDownLatch.countDown();
}
}
});
}
//線程阻塞,知道countDownLatch計數值=0
countDownLatch.await();
System.out.println(count);
//關閉線程池
executorService.shutdown();
}
}
輸出結果:50005000
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。