一、介紹
1、Java 5.0 在 java.util.concurrent 包中提供了多種併發容器類來改進同步容器 的性能。
2、 CountDownLatch 一個同步輔助類,在完成一組正在其他線程中執行的操作 之前,它允許一個或多個線程一直等待。
3、 閉鎖可以延遲線程的進度直到其到達終止狀態,閉鎖可以用來確保某些活動直到其他活動都完成才繼續執行:
- 確保某個計算在其需要的所有資源都被初始化之後才繼續執行;
- 確保某個服務在其依賴的所有其他服務都已經啓動之後才啓動;
- 等待直到某個操作所有參與者都準備就緒再繼續執行。
二、代碼案例
package com.example.juc;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
/**
* @author haoxiansheng
* CountDownLatch: 閉鎖,在完成某些運算,只有其他所有線程的運算全部完成,當前運算才能繼續執行
*/
@Slf4j
public class CountDownLatchTest {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(5);
LatchDemo latchDemo = new LatchDemo(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
new Thread(latchDemo).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
log.info("耗費時間爲=>{}", (end - start));
}
}
class LatchDemo implements Runnable {
private CountDownLatch latch;
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
latch.countDown();
}
}
}
}