为了账号安全,请及时绑定邮箱和手机立即绑定

如何获知new Runnable(){run(){}}中的逻辑执行完毕?

如何获知new Runnable(){run(){}}中的逻辑执行完毕?

喵喔喔 2019-03-20 22:19:44
如何知道写在runnable()中的逻辑执行完毕??
查看完整描述

2 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

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 原答案里的其他回答也有参考价值


查看完整回答
反对 回复 2019-04-24
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

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上的原答案

查看完整回答
反对 回复 2019-04-24
  • 2 回答
  • 0 关注
  • 1135 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号