我倾向于CyclicBarrier并且我写了这个演示。
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();
}
}
}
正如我所料,该程序打印了五个tripped
并退出。
tripped
tripped
tripped
tripped
tripped
我的问题是CyclicBarrier
实例在最后一次await()
到达时自行重置?所以输出是预期的?我找不到任何形容词。