我正在尝试 Java 8 并发性的第一步。 在下面的代码示例中,抛出异常是因为我的任务 hibernate 了 2 秒。关机功能等待 5 秒以终止。因此,只执行了两个循环。是否有动态解决方案而不是计算执行可能花费的最长时间并调整 awaitTermination() 方法的值?
public class Application {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(1);
IntStream.range(0, 10).forEach(i ->
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Hello");
} catch (InterruptedException e) {
throw new IllegalStateException("Task interrupted", e);
}
})
);
shutdown(executor);
}
private static void shutdown(ExecutorService executor) {
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println("tasks interrupted");
} finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
}
}
最佳答案
除了@AdamSkyWalker 提到的内容之外,您还可以使用 CountDownLatch,因为您已经知道线程数(在本例中为 10 个)。
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
final CountDownLatch latch = new CountDownLatch(10);
IntStream.range(0, 10).forEach(i ->
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Hello");
} catch (InterruptedException e) {
throw new IllegalStateException("Task interrupted", e);
} finally {
latch.countDown();
}
})
);
latch.await();
}
}
我写了一个post有时回过头来比较 CountDownLatch
、Semaphore
和 CyclicBarrier
,这会对您有所帮助。
关于Java 8 并发 - 等待任务关闭执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863715/