我遇到了這個併發問題,我一直在撓頭我的好幾天。等待所有任務(未知號碼)完成 - ThreadPoolExecutor
基本上,我希望我的ThreadPoolExecutor在關閉之前等待所有任務(任務數量未知)完成。
public class AutoShutdownThreadPoolExecutor extends ThreadPoolExecutor{
private static final Logger logger = Logger.getLogger(AutoShutdownThreadPoolExecutor.class);
private int executing = 0;
private ReentrantLock lock = new ReentrantLock();
private final Condition newTaskCondition = lock.newCondition();
private final int WAIT_FOR_NEW_TASK = 120000;
public AutoShutdownThreadPoolExecutor(int coorPoolSize, int maxPoolSize, long keepAliveTime,
TimeUnit seconds, BlockingQueue<Runnable> queue) {
super(coorPoolSize, maxPoolSize, keepAliveTime, seconds, queue);
}
@Override
public void execute(Runnable command) {
lock.lock();
executing++;
lock.unlock();
super.execute(command);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
try{
lock.lock();
int count = executing--;
if(count == 0) {
newTaskCondition.await(WAIT_FOR_NEW_TASK, TimeUnit.MILLISECONDS);
if(count == 0){
this.shutdown();
logger.info("Shutting down Executor...");
}
}
}
catch (InterruptedException e) {
logger.error("Sleeping task interrupted", e);
}
finally{
lock.unlock();
}
}
}
的目的是,爲任務計數器任務檢查(執行),如果它等於0,它阻止了一段時間,後來釋放其鎖,以便其他任務可能要執行的機會,不要太早關閉執行者。
但是,它沒有發生。所有4個線程在執行程序進入等待狀態:
"pool-1-thread-4" prio=6 tid=0x034a1000 nid=0x2d0 waiting on condition [0x039cf000]
"pool-1-thread-3" prio=6 tid=0x034d0400 nid=0x1328 waiting on condition [0x0397f000]
"pool-1-thread-2" prio=6 tid=0x03493400 nid=0x15ec waiting on condition [0x0392f000]
"pool-1-thread-1" prio=6 tid=0x034c3800 nid=0x1fe4 waiting on condition [0x038df000]
如果我在運行的類把日誌語句(應該減緩線向下),這個問題似乎消失了。
public void run() {
// logger.info("Starting task" + taskName);
try {
//doTask();
}
catch (Exception e){
logger.error("task " + taskName + " failed", e);
}
}
的問題是,類似這樣的帖子 Java ExecutorService: awaitTermination of all recursively created tasks
,我都按照原來的海報解決方案,試圖解決afterExecute()的比賽條件,但它不工作。
請幫忙解釋一下。 謝謝。
使用CountDownLatch怎麼樣? – 2012-03-30 03:10:57
任務數量事先未知。該程序將掃描其子文件夾中所有文件的目錄,並在每個文件上執行一些編號處理任務。 – TommyQ 2012-03-30 03:15:03