我有以下程序,我正在使用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.");
}
输出
二是等待。
三是等待。
一是等待。
一个已完成。
二是完成。
三是完成。