Java 中并发执行代码,并等待所有线程执行完成。
CountDownLatch latch = new CountDownLatch(selectors.length);
ExecutorService executor = Executors.newFixedThreadPool(selectors.length);
long[] durations = new long[selectors.length];
for (int i = 0; i < selectors.length; i++) {
final int index = i;
executor.submit(() -> {
long start = System.currentTimeMillis();
durations[index] = System.currentTimeMillis() - start;
latch.countDown();
});
}
try {
latch.await();
String s = "Duration: " + join(durations, ",");
log.debug("并发 " + s);
} catch (Exception e) {
}