在多執行緒中,有時候需要等待所有執行緒執行完成後才讓繼續往下執行,如查詢結果彙總等。下面列舉兩種等待方式:
方式一: 利用 countdownlatch 類完成。
示例:
// 按任務總量建立計數器jdk原始碼示例參考:final countdownlatch countdownlatch = new countdownlatch(sourcelist.size() - 1);
for (int i = 1; i < sourcelist.size(); i++)
finally
}});
}try
catch
(exception e)
class driverview code*} *
* class worker implements
runnable
* public
void
run() catch (interruptedexception ex) {} //
return;
*} *
* void
dowork()
*}}* class driver2
*} *
* class workerrunnable implements
runnable
* public
void
run() catch (interruptedexception ex) {} //
return;
*} *
* void
dowork()
* }}
方式二: 利用任務自身的阻塞能力阻塞主線程執行。
示例:
private threadpoolexecutor threadpoolexecutor = null;private
void
init()
//批量任務生成
list>> tasklist = new linkedlist<>();
for(string sql : sqllist)
});tasklist.add(task);}//
批量執行
for (futuretask>task : tasklist)
//結果彙總
long cnt = 0l;
for (futuretask>task : tasklist)
} catch
(throwable e)
}
與 submit 類似的,參考:
Python等待所有執行緒任務完成
import threading import time import random def takesleep id,name print name id 執行緒開始執行.time.sleep random.randint 0,3 print name id 執行緒任務結束 print 主程式開始...
多執行緒 如何確定所有任務都執行完成了?
20180502更新 今天學習到了乙個比較強大的類 executorcompletionservice,它是將 executor和blockqueue結合的jdk類,其實現的主要目的是 提交任務執行緒,每乙個執行緒任務直線完成後,將返回值放在阻塞佇列中,然後可以通過阻塞佇列的take 方法返回 對應...
多執行緒主線程等待子執行緒都執行完成才執行
1.建立countdownlatch物件,設定子執行緒的數量 countdownlatch countdownlatch new countdownlatch size 其中size就是子執行緒的數量 2.開啟執行緒執行方法 壓縮生成.tbwj file bidfile ziputil.zip te...