- CountDownLatch is used to when you want a thread to wait until one or more events have occurred.
- It is initially created with a count of the number of events that must occur before the latch is released.
- Each time an event happens, the count is decremented. and the latch is opened when the count reaches to zero.
import java.util.concurrent.CountDownLatch;
class Task implements Runnable {
CountDownLatch cdl;
Task(CountDownLatch cdl){
this.cdl = cdl;
}
/**
* Runs this operation.
*/
@Override
public void run() {
String name = Thread.currentThread().getName();
try {
for(int i=1;i<=3;i++){
Thread.sleep(10);
System.out.println("Event >> " + i);
cdl.countDown(); // decrement count
}
} catch (InterruptedException ex) {
System.out.println("thread interrupted");
}
}
}
public class Main {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(3); // latch that requires 3 events to occur before it opens
new Thread(new Task(cdl)).start();
try {
cdl.await();
} catch (InterruptedException e) {
System.out.println("Exception occurred");
}
}
}