import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Thread workerThread = new Thread(() -> { // Do some work... System.out.println("Worker: Work complete!"); latch.countDown(); }); workerThread.start(); System.out.println("Main: Waiting for worker thread to finish..."); latch.await(); System.out.println("Main: Worker thread finished!"); } }
import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { int numWorkers = 5; CountDownLatch latch = new CountDownLatch(numWorkers); for (int i = 0; i < numWorkers; i++) { Thread workerThread = new Thread(() -> { // Do some work... System.out.println("Worker: Work complete!"); latch.countDown(); }); workerThread.start(); } System.out.println("Main: Waiting for all worker threads to finish..."); latch.await(); System.out.println("Main: All worker threads finished!"); } }This example uses a CountDownLatch with a count of 5, which means the main thread will wait for all 5 worker threads to call latch.countDown() before proceeding. The CountDownLatch class is part of the java.util.concurrent package.