I have the following program, where I am using java.util.concurrent.CountDownLatch
and without using await()
method it's working fine.
I am new to concurrency and want to know the purpose of await()
. In CyclicBarrier
I can understand why await()
is needed, but why in 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
implements 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.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.