CountDownLatch,一個同步輔助類,在完成一組正在其餘線程中執行的操做以前,它容許一個或多個線程一直等待。html
主要方法java
public CountDownLatch(int count);this
public void countDown();線程
public void await() throws InterruptedException
code
構造方法參數指定了計數的次數htm
countDown方法,當前線程調用此方法,則計數減一get
awaint方法,調用此方法會一直阻塞當前線程,直到計時器的值爲0同步
例子it
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() { ... } }