CountDownLatch 中 await() 的作用是什么?

What is the purpose of await() in CountDownLatch?

我有以下程序,我在其中使用 java.util.concurrent.CountDownLatch 并且没有使用 await() 方法,它工作正常。

我是并发新手,想知道 await() 的用途。在 CyclicBarrier 中我可以理解为什么需要 await(),但为什么在 CountDownLatch 中?

Class CountDownLatchSimple:

public static void main(String args[]) {
  CountDownLatch latch = new CountDownLatch(3);
  Thread one = new Thread(new Runner(latch),"one");
  Thread two = new Thread(new Runner(latch), "two");
  Thread three = new Thread(new Runner(latch), "three");

  // Starting all the threads
  one.start(); two.start(); three.start();
  
}

Class Runner 实现 Runnable:

CountDownLatch latch;

public Runner(CountDownLatch latch) {
    this.latch = latch;
}

@Override
public void run() {
    System.out.println(Thread.currentThread().getName()+" is Waiting.");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    latch.countDown();
    System.out.println(Thread.currentThread().getName()+" is Completed.");
}

输出

two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.

CountDownLatch是同步原语,用于等待所有线程完成某个动作。

每个线程都应该通过调用 countDown() 方法来标记完成的工作。等待动作完成的人应该调用 await() 方法。这将无限期地等待,直到所有线程通过调用 countDown() 将工作标记为已处理。例如,主线程可以继续处理工作人员的结果。

因此在您的示例中,在 main() 方法的末尾调用 await() 是有意义的:

latch.await();

注意:当然还有很多其他用例,它们不一定是线程,但通常异步运行的任何东西,同一个锁存器可以被同一个任务递减多次等等。上面只描述了一个CountDownLatch.

的常见用例