About CountDownLatch
CountDownLatch is available in java.util.concurrent packageCountDownLatch is introduced in concurrency framework and it allows more than one threads to wait for particular set of operations to finish.When CountDownLatch is initialized then it is having some count value and that count value is decremented by calling to the countDown() method. A thread which is waiting for this count value to reach zero, it calls await() method. Calling await() method will block the thread until the count value is decreament to zero.
So, this way the waiting thread will wait until all the required operation or processes finish their execution.
CountDownLatch latch = new CountDownLatch(3); MyWaiter waiter = new MyWaiter(latch); Worker worker = new Worker (latch); new Thread(waiter).start(); new Thread(worker).start(); public class Worker implements Runnable { CountDownLatch latch = null; public Worker(CountDownLatch latch) { this.latch = latch; } public void run() { try { Thread.sleep(1000); this.latch.countDown(); Thread.sleep(1000); this.latch.countDown(); Thread.sleep(1000); this.latch.countDown(); } catch (Exception e) { } } } public class MyWaiter implements Runnable{ CountDownLatch latch = null; public MyWaiter(CountDownLatch latch) { this.latch = latch; } public void run() { try { latch.await(); } catch (Exception e) { } System.out.println("MyWaiter Released"); } }