Java CountDownLatch Example
In this example we will discuss about the classjava.util.concurrent.CountDownLatch.java.util.concurrent.CountDownLatch is a synchronization mechanism that allows one or more threads to wait until a set of operations being performed in other threads completes.
1. How CountDownLatch works
Ajava.util.concurrent.CountDownLatch is initialized with a given count. The constructor ofjava.util.concurrent.CountDownLatch is defined as follows:
CountDownLatch(int count)
Constructs a CountDownLatch initialized with the given count.
Then, theawait() method blocks the main thread until the current count reaches zero. This will happen after continuous invocations of thecountDown() method, which decrements the latch counter. When this latch counter reaches zero, all waiting threads are released and any subsequent invocations ofawait return immediately.
2. CountDownLatch example
In this section we will show a simple example of usingjava.util.concurrent.CountDownLatch.
First, create a java class namedCountDownLatchExample.java with the following code:
CountDownLatchExample.java
package com.javacodegeeks.java.util.concurrent.countdownlatch;import java.util.concurrent.*;public class CountDownLatchExample {public static void main(String args[]) {final CountDownLatch latch = new CountDownLatch(3);Thread testThread1 = new Thread(new TestThread("FirstThread", latch));Thread testThread2 = new Thread(new TestThread("SecondThread", latch));Thread testThread3 = new Thread(new TestThread("ThirdThread", latch));testThread1.start();testThread2.start();testThread3.start();try {latch.await();} catch (InterruptedException ie) {}System.out.println("All threads have started");}}In the main thread, we initialize theCountDownLatch with count 3 and we start three other threads. The main thread will be blocked until the count reaches zero.
Also, create a java class namedTestThread.java with the following code:
TestThread.java
package com.javacodegeeks.java.util.concurrent.countdownlatch;import java.util.concurrent.CountDownLatch;public class TestThread extends Thread {private String name;private CountDownLatch latch;public TestThread(String name, CountDownLatch latch) {this.name = name;this.latch = latch;}public void run() {System.out.println(name + " : started");try {Thread.sleep(2000);} catch (Exception e) {}latch.countDown();}}Εach of the other threads decrement theCountDownLatch.
If we run the above code, we will have the following results:
- Output:
FirstThread : startedSecondThread : startedThirdThread : startedAll threads have started
Download the source code
This was an example of how to usejava.util.concurrent.CountDownLatch class.
You can download the full source code of this example here :CountDownLatchExample

Thank you!
We will contact you soon.




