I'm leaning about the CyclicBarrier and I wrote this demo.
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import static java.util.concurrent.ThreadLocalRandom.current;
public class CyclicBarrierDemo {
public static void main(final String[] args) {
final int threads = 100;
final CyclicBarrier barrier
= new CyclicBarrier(threads, () -> System.out.println("tripped"));
final int rounds = 5;
for (int i = 0; i < threads; i++) {
new Thread(() -> {
for (int j = 0; j < rounds; j++) {
try {
Thread.sleep(current().nextLong(1000L));
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace(System.err);
return;
}
}
}).start();
}
}
}
The program prints five tripped
and quits, as I expected.
tripped
tripped
tripped
tripped
tripped
My question is that the CyclicBarrier
instance reset itself when the last await()
arrived? So that the output is expected? I couldn't find any words for that.