栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何检查在ExecutorService上运行的所有任务是否已完成

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何检查在ExecutorService上运行的所有任务是否已完成

如果使用,没有一种干净的方法来检查所有Runnable是否都已完成

ExecutorService.execute(Runnable)
。除非您在Runnable本身中构建了一种机制来这样做(在我看来这是草率的)。

相反:
使用

ExecutorService.submit(Runnable)
。此方法将返回a
Future<?>
,它是a的结果的句柄
Runnable
。使用期货提供了一种检查结果的干净方法。

您要做的只是维护您提交的期货列表,然后可以遍历整个期货列表,然后:
A)等待所有期货以封闭方式完成,或者
B)检查是否所有期货以非阻塞方式进行。

这是一个代码示例:

List<Future<?>> futures = new ArrayList<Future<?>>();ExecutorService exec = Executors.newFixedThreadPool(5);// Instead of using exec.execute() use exec.submit()// because it returns a monitorable futurewhile((item = stack.pollFirst()) != null){    Runnable worker = new Solider(this, item);    Future<?> f = exec.submit(worker);    futures.add(f);}// A) Await all runnables to be done (blocking)for(Future<?> future : futures)    future.get(); // get will block until the future is done// B) Check if all runnables are done (non-blocking)boolean allDone = true;for(Future<?> future : futures){    allDone &= future.isDone(); // check if future is done}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号