功能概述
一個同步工具,允許一個或多個線程等待,直到一系列在其他線程的操作完成。
核心的方法
- 構造函數(shù)
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
- wait 方法
- 說明:除非線程被打斷(Thread#interrupt),否則線程會被等待,直到 計數(shù) count 為0。
public void await() throws InterruptedException {
...
}
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
...
}
- countDown
- 說明:計數(shù)器減一,如果計數(shù)器為0,則釋放所有等待的線程。
public void countDown() {
...
}
使用場景
1.實現(xiàn)多線程同時 進行 執(zhí)行
2.開始執(zhí)行前等待n個線程完成各自任務
下面是兩種使用場景的經典demo。
經典的demo
demo 1
class Driver {
void main() throws InterruptedException {
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; ++i) // create and start threads
new Thread(new Worker(startSignal, doneSignal)).start();
doSomethingElse(); // don't let run yet
startSignal.countDown(); // let all threads proceed
doSomethingElse();
doneSignal.await(); // wait for all to finish
}
}
class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() { ... }
}}
demo2
class Driver2 {
void main() throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
Executor e = ...
for (int i = 0; i < N; ++i) // create and start threads
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
try {
doWork(i);
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() { ... }
}}