我遇到了这个并发问题,我一直在挠头我的好几天。等待所有任务(未知号码)完成 - 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