6

我有以下程序,我正在使用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();
  
}

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.");
}

输出

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

4

1 回答 1

7

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

Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.

So in your example it would make sense to call await() at the end of main() method:

latch.await();

Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

于 2017-01-26T04:24:03.963 回答