Java / Java Multithreading
What is CountDownLatch in Java?
CountDownLatch is a synchronizer type which allows one Thread to wait for one or more Threads before starts processing.
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is not a reusable phenomenon, the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
package CountDownLatchExample; import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { static final CountDownLatch latch = new CountDownLatch(2); public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread(latch); new Thread(thread).start(); new Thread(thread).start(); latch.await(); System.out.println(Thread.currentThread().getName() + " done."); } } class MyThread implements Runnable { CountDownLatch latch; MyThread(CountDownLatch latch) { this.latch = latch; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " completed."); latch.countDown(); } }
More Related questions...