我有以下程序,在其中使用了java.util.concurrent.CountDownLatch,并且在没有使用await()方法的情况下它可以正常工作。
我是并发编程的新手,想知道await()的目的。在CyclicBarrier中,我可以理解为什么需要await(),但在CountDownLatch中为什么需要呢?
CountDownLatchSimple类:
我是并发编程的新手,想知道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.");
}
输出
two 正在等待。
three 正在等待。
one 正在等待。
one 已完成。
two 已完成。
three 已完成。