CountDownLatch 中 await() 的目的是什么?

New*_*ava 5 concurrency multithreading countdownlatch java.util.concurrent cyclicbarrier

我有以下程序,我正在使用java.util.concurrent.CountDownLatch和不使用await()方法它工作正常。

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

班级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();
  
}
Run Code Online (Sandbox Code Playgroud)

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.");
}
Run Code Online (Sandbox Code Playgroud)

输出

二是等待。
三是等待。
一个是等待。
一个是完成。
二是完成。
三是完成。

Zby*_*000 9

CountDownLatch是用于等待所有线程完成某些操作的同步原语。

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

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

latch.await();
Run Code Online (Sandbox Code Playgroud)

注意:当然还有许多其他用例,它们不需要是线程,但无论通常异步运行,相同的锁存器都可以通过相同的任务递减多次,等等。上面仅描述了CountDownLatch.