gpt4 book ai didi

Java 8 并发 - 等待任务关闭执行器

转载 作者:搜寻专家 更新时间:2023-11-01 02:19:58 25 4
gpt4 key购买 nike

我正在尝试 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有时回过头来比较 CountDownLatchSemaphoreCyclicBarrier,这会对您有所帮助。

关于Java 8 并发 - 等待任务关闭执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com