首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java 8并发-等待任务关闭executor

Java 8并发-等待任务关闭executor
EN

Stack Overflow用户
提问于 2018-02-19 18:08:28
回答 1查看 212关注 0票数 4

我正在尝试Java 8并发的第一步。在下面的代码示例中,因为my tasks休眠2秒而引发异常。关机功能等待5秒后终止。因此,只执行两个循环。有没有动态的解决方案,而不是计算执行所需的最大时间并调整awaitTermination()-method的值?

代码语言:javascript
复制
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();
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-19 18:19:00

除了@AdamSkyWalker提到的,你还可以使用CountDownLatch,因为你已经知道线程的编号(在本例中是10)。

代码语言:javascript
复制
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();


    }
}

我曾经写过一个比较CountDownLatchSemaphoreCyclicBarrierpost,它会对你有帮助。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48863715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档