等待所有任务(未知数量)完成 - ThreadPoolExecutor

Tom*_*myQ 5 java concurrency

我遇到了这个并发问题,我已经挠头好几天了。

基本上,我希望我的 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

目的是任务检查任务计数器(正在执行),如果它等于 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]
Run Code Online (Sandbox Code Playgroud)

如果我在 Runnable 类中放置一条日志语句(应该会减慢线程速度),问题似乎就消失了。

public void run() {
    //  logger.info("Starting task" + taskName);
        try {
            //doTask();
        }
        catch (Exception e){
            logger.error("task " + taskName + " failed", e);
        }
}
Run Code Online (Sandbox Code Playgroud)

问题类似于这篇文章 Java ExecutorService:awaitTermination of all recursively Created Task

我采用了原始海报解决方案,并尝试解决 afterExecute() 中的竞争条件,但它不起作用。

请帮助阐明这一点。谢谢。

bdo*_*lan 2

你有你的任务在等待newTaskCondition,但没有任何信号表明这种情况。所以你的线程都堆积起来,都在等待newTaskCondition,直到超时。此外,阻塞afterExecute会延迟任务的完成,因此这可能不是您想要做的。

如果您想让它等待一段时间以查看是否有更多工作完成,那么此功能已经存在。只需调用setKeepAliveTime设置等待多长时间,并设置allowCoreThreadTimeOut以确保所有线程(包括核心线程)都可以终止。