Related Topics

JAVA Programming
import java.util.concurrent.CountDownLatch;
public class Example {
public static void main(String[] args) throws InterruptedException {
int numThreads = 5;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(() -> {
// Do some work
latch.countDown(); // Signal that the work is done
});
t.start();
}
latch.await(); // Wait for all threads to finish
System.out.println("All threads have finished");
}
}
In this example, we create a CountDownLatch
with a count of 5, and then start 5 threads that do some work and then call countDown()
on the latch to signal that they have finished. The main
thread then calls await()
on the latch to wait for all 5 threads to finish before printing a message. This ensures that the message is only printed once all of the threads have completed their work.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.