【开发百宝箱系列】- CountDownLunch标准用法

CountDownLunch 标准用法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&#039;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) {
        // error
    } // return;
  }

  void doWork() { ... }

}

CountDownLatch 标准用法2:基于线程池

class Driver2 {
   void main() throws InterruptedException {
     CountDownLatch doneSignal = new CountDownLatch(N);
     ExecutorService e = Executors.newFixedThreadPool(N);

     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) {
        // error
     } // return;
   }

   void doWork() { ... }
}