我需要在某个检查点同步一些线程,并且只有在所有线程都达到这一点之后,它们才应该继续。有没有简单的构造?
for (int v = 0; v < 10; v++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
doFirst();
//checkpoint
doSecond();
} catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
}
最佳答案
如果您知道确切的线程数,则可以使用java.util.concurrent中的 CountDownLatch
。
// First initialize latch with your number of threads
CountDownLatch latch = new CountDownLatch(N);
// Then give this instance of latch to each of your threads
// and finally at your checkpoint do
latch.countDown();
latch.await();
就这样。