CountDownLatch:用于多線程并行執行
例:
@Slf4j
public class CountDownLatchDemo {
private static volatile int index = 0;
public static void main(String[] args) throws InterruptedException {
//建立倒計數器,指定計數數量為3
CountDownLatch countDownLatch = new CountDownLatch(3);
ThreadPoolManager.ThreadPool threadPool = ThreadPoolManager.getThreadPool();
for (int i = 1; i < 4; i++) {
int s=++index;
threadPool.execute(() -> {
log.info(s + " runing " + System.currentTimeMillis());
try {
Thread.sleep(1000);
log.info(s + " run end " + System.currentTimeMillis());
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
} finally {
//通知CountDownLatch有一個線程已經準備完畢,倒計數器可以減一了
countDownLatch.countDown();
}
});
}
//要求主線程需等所有線程準備好後,并行執行完畢後才能繼續執行
countDownLatch.await();
//關閉線程池
threadPool.shutdown();
log.debug("main Thread end");
}
}
ThreadPoolManager.ThreadPool為自寫的一個線程池工具,代碼詳情
輸出:
1 runing 1564386456075
2 runing 1564386456076
3 runing 1564386456076
2 run end 1564386457080
1 run end 1564386457080
3 run end 1564386457080
main Thread end
各線程執行順序可能與輸出不一緻,但是主線程必須在CountDownLatch倒計數器執行為0時才會繼續執行。
注意:
- CountDownLatch指定計數數量如小于線程數,那麼超出的線程将可能不能達到并行的要求;
- CountDownLatch指定的計數數量大于線程數,那主線程将無法執行完畢。
更多文章:
CSDN部落格
簡書部落格
公衆号:代碼小搬運