我傾向於CyclicBarrier,我寫了這個演示。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();
}
}
}
該程序打印5 tripped
和退出,如我所料。
tripped
tripped
tripped
tripped
tripped
我的問題是,CyclicBarrier
實例自行復位,當到達最後await()
?這樣的產量預計?我找不到任何文字。
謝謝。官方apidoc應該提到這一點! –
很好的解釋 – rvit34