CountDownLatch

功能概述

一个同步工具,允许一个或多个线程等待,直到一系列在其他线程的操作完成。

核心的方法

  • 构造函数
public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
  • wait 方法
    • 说明:除非线程被打断(Thread#interrupt),否则线程会被等待,直到 计数 count 为0。
public void await() throws InterruptedException {
...
}
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
...
}
  • countDown
    • 说明:计数器减一,如果计数器为0,则释放所有等待的线程。
public void countDown() {
...
}

使用场景

1.实现多线程同时 进行 执行
2.开始执行前等待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() { ... }
}}

你可能感兴趣的:(CountDownLatch)