【问题标题】:how to make executor service wait until all thread finish如何让执行器服务等到所有线程完成
【发布时间】:2014-05-21 19:35:28
【问题描述】:

我使用执行器服务来启动多个线程来向 api 发送请求并取回数据。有时我看到一些线程还没有完成他们的工作,服务已经杀死了那个线程,我怎样才能强制服务等到线程完成他们的工作?

这是我的代码:

        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<List<Book>>> futures = Lists.newArrayList();
        final ObjectMapper mapper1 = new ObjectMapper();
        for (final Author a : authors) {
            futures.add(pool.submit(new Callable<List<Book>>() {
                @Override
                public List<Book> call() throws Exception {
                    String urlStr = "http://localhost/api/book?limit=5000&authorId=" + a.getId();

                    List<JsonBook> Jsbooks = mapper1.readValue(
                            new URL(urlStr), BOOK_LIST_TYPE_REFERENCE);

                    List<Book> books = Lists.newArrayList();
                    for (JsonBook jsonBook : Jsbooks) {
                        books.add(jsonBook.toAvro());
                    }

                    return books;
                }
            }));
        }
        pool.shutdown();
        pool.awaitTermination(3, TimeUnit.MINUTES);

      List<Book> bookList = Lists.newArrayList();
    for (Future<List<Book>> future : futures) {
        if (!future.isDone()) {
           LogUtil.info("future " + future.toString());  <-- future not finished yet 
           throw new RuntimeException("Future to retrieve books: " + future + " did not complete");

}
        bookList.addAll(future.get());
    }

我在 (!future.isDone()) 块中看到了一些异常。当执行程序服务关闭时,我如何确保每个未来都完成?

【问题讨论】:

标签: future executorservice


【解决方案1】:

我喜欢使用倒计时锁。

将锁存器设置为您正在迭代的大小并将该锁存器传递给您的可调用对象,然后在您的运行/调用方法中有一个尝试/最终块来减少倒计时锁存器。

在所有内容都排入您的 executor 服务之后,只需调用您的锁存器的 await 方法,该方法将一直阻塞,直到全部完成。届时你所有的 callables 都将完成,你可以正常关闭你的 executor 服务。

此链接有一个如何设置的示例。 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 2014-10-05
    • 2014-05-10
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多