Java

CountDownLatch — Wait for N Events

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Block one or more threads until a count of events occurs. Set the count up front; each event calls `countDown()`; waiters call `await()`. Classic "wait until all workers are ready" pattern.
Java
Raw
import java.util.concurrent.*;

class Demo {
    void example() throws Exception {
        int workerCount = 5;
        var ready = new CountDownLatch(workerCount);
        var start = new CountDownLatch(1);
        var done  = new CountDownLatch(workerCount);

        for (int i = 0; i < workerCount; i++) {
            int id = i;
            new Thread(() -> {
                try {
                    System.out.println("[" + id + "] ready");
                    ready.countDown();              // I'm ready
                    start.await();                  // wait for the gun
                    System.out.println("[" + id + "] running");
                    Thread.sleep(100);
                    done.countDown();               // I'm done
                } catch (InterruptedException ignored) {}
            }).start();
        }

        ready.await();                              // wait until all 5 are ready
        System.out.println("all ready — starting");
        start.countDown();                          // fire the gun
        done.await();                               // wait for all to finish
        System.out.println("all done");
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.