首页  编辑  

Java 多线程并发执行并等待完成的方法

Tags: /Java/   Date Created:
Java 中并发执行代码,并等待所有线程执行完成。
CountDownLatch latch = new CountDownLatch(selectors.length);
ExecutorService executor = Executors.newFixedThreadPool(selectors.length);
long[] durations = new long[selectors.length]; // thread time duration

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) {
    // Oops...
}