threads
CountDownLatch example
In this example we shall show you how to use a CountDownLatch. The CountDownLatch is 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. The CountDownLatch of the example is derscibed below:
- We have created a class,
MyThread
that implements the Runnable. It has a CountDownLatch variable and in its constructor it creates a new Thread and causes the thread’s execution calling itsstart()
API method. It overrides therun()
API method of Runnable, where in a loop statement it calls thecountDown()
API method of CountDownLatch. The method decrements the count of the latch, releasing all waiting threads if the count reaches zero. - We have created a new CountDownLatch, using
CountDownLatch(int count)
constructor that constructs a CountDownLatch initialized with the given count. - Then we create a new
MyThread
, using this latch. Callingawait()
API method of CountDownLatch causes the current thread to wait until the latch has counted down to zero, unless it is interrupted. - If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until the count reaches zero due to invocations of the countDown or until some other thread interrupts the current thread,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String args[]) { CountDownLatch cdl = new CountDownLatch(5); new MyThread(cdl); try { cdl.await(); } catch (InterruptedException exc) { System.out.println(exc); } System.out.println("Finish"); } } class MyThread implements Runnable { CountDownLatch latch; MyThread(CountDownLatch cdl) { latch = cdl; new Thread(this).start(); } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(i); latch.countDown(); } } }
Output:
0
1
2
3
4
Finish
This was an example of how to use a CountDownLatch in Java.