如何知道写在runnable()中的逻辑执行完毕??
光阴似箭催人老,日月如移越少年。
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 原答案裡的其他答案也有參考價值
StackOverflow上的原答案。
這裡有個假設是,1分鐘之內,所有task都會執行完畢, 場景符合的話這種是最簡單的。
如果超時時間範圍內可能執行不成功,或無法評估執行時間的場景。
使用這個類,是不是比較方便一點?
方法可能有多種,適合場景的才是最好的。
樓上貼的stackoverflow 原答案裡的其他答案也有參考價值