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

标签 java concurrency

我正在尝试 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/

相关文章:

java - 如何在持久化时忽略 hibernate 实体中的子类

c++ - 为什么 Go 不显示内存重新排序?

java - 避免使用全局变量,同时允许访问另一个线程拥有的对象

swift - 在后台线程中使用 async-await 有什么好处?

java - 如何在android中为pdf查看器制作注释,如突出显示、删除线、下划线、绘制、添加文本等?

java - 我如何从 boyh recyclerview 和存储 android studio 中删除项目

java - 在 java 中不使用乘法、除法和模运算符来除两个整数

java - 在 Java 中按值对数组元素进行分组(2 × 2、3 × 3 等)

concurrency - 缓存一致性文献一般只指存储缓冲区而不是读取缓冲区。然而,不知何故,两者都需要?

Scala final 与 val 的并发可见性