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");
}
}
Create a free account and build your private vault. Share publicly whenever you want.