java - 如何获知new Runnable(){run(){}}中的逻辑执行完毕?
大家讲道理
大家讲道理 2017-04-18 10:01:57
0
2
521

如何知道写在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 原答案裡的其他答案也有參考價值

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板