java - 如何获知new Runnable(){run(){}}中的逻辑执行完毕?
大家讲道理
大家讲道理 2017-04-18 10:01:57
[Java讨论组]

如何知道写在runnable()中的逻辑执行完毕??

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
巴扎黑
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();
try{
    //等待线程执行完毕
    boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);
    if (finished){
        //do something
    }
}catch(InterruptedException e){
    //timeout
}

StackOverflow上的原答案。

怪我咯
boolean awaitTermination(long timeout,TimeUnit unit)throws InterruptedException

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.  

这里有个假设是,1分钟之内,所有task都会执行完毕, 场景符合的话这种是最简单的。
如果超时时间范围内可能执行不成功,或者无法评估执行时间的场景。
使用这个类,是不是更方便一点?

java.util.concurrent.CountDownLatch 

方法可能有多种,适合场景的才是最好的。
楼上贴的stackoverflow 原答案里的其他回答也有参考价值

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号