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 <1>
startSignal.countDown(); // let all threads proceed <2>
doSomethingElse(); // <3>
doneSignal.await(); // wait for all to finish <4>
}
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(); // <5>
doWork();
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
void doWork() { ... }
}}
class Driver2 { // ...
Executor e = ...
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
class WorkerRunnable implements Runnable {
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.i = i;
doWork(i);
文章有问题?点此查看未经处理的缓存