如何等待在ThreadPoolExecutor的所有任务,而无需关闭执行人完成? [英] How to wait for all tasks in an ThreadPoolExecutor to finish without shutting down the Executor?

查看:4555
本文介绍了如何等待在ThreadPoolExecutor的所有任务,而无需关闭执行人完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用关机() awaitTermination(),因为它是可能的新任务将被添加到ThreadPoolExecutor的,而它正在等待。

I can't use shutdown() and awaitTermination() because it is possible new tasks will be added to the ThreadPoolExecutor while it is waiting.

所以我在寻找一种方式来等待的ThreadPoolExecutor已经清空它的队列中,并完成了这一切的任务,而无需从该点之前被停止添加新的任务。

So I'm looking for a way to wait until the ThreadPoolExecutor has emptied it's queue and finished all of it's tasks without stopping new tasks from being added before that point.

如果这有什么差别,这是Android。

If it makes any difference, this is for Android.

感谢

更新:许多星期后重新审视这个之后,我发现,修改后的CountDownLatch在这种情况下工作更好地为我。我会继续标志着答案,因为它更适用于我问。

Update: Many weeks later after revisiting this, I discovered that a modified CountDownLatch worked better for me in this case. I'll keep the answer marked because it applies more to what I asked.

推荐答案

如果您有兴趣了解一个特定的任务完成时,还是有一定批量的任务,您可以使用 ExecutorService.submit(可运行)。调用此方法返回一个未来对象,它可以被放置到集合,你的主线程然后遍历调用的Future.get()的每一个。这将导致你的主线程停止执行,直到的ExecutorService 处理完所有的的Runnable 任务。

If you are interested in knowing when a certain task completes, or a certain batch of tasks, you may use ExecutorService.submit(Runnable). Invoking this method returns a Future object which may be placed into a Collection which your main thread will then iterate over calling Future.get() for each one. This will cause your main thread to halt execution until the ExecutorService has processed all of the Runnable tasks.

Collection<Future<?>> futures = new LinkedList<Future<?>>();
futures.add(executorService.submit(myRunnable));
for (Future<?> future:futures) {
    future.get();
}

这篇关于如何等待在ThreadPoolExecutor的所有任务,而无需关闭执行人完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆