ThreadPoolTask​​Executor正常关闭

use*_*636 1 java spring multithreading interrupt executor

我正在使用Spring(v4)ThreadPoolTaskExecutor执行一些连续的可运行任务。当应用程序关闭时,我希望正常关闭执行器,以便任务有一些时间在继续关闭之前完成其迭代。如果活动任务在执行者等待时间到期之前(例如ThreadPoolTaskExecutor.setAwaitTerminationSeconds())完成了其迭代,则我不希望它开始另一个迭代。到目前为止,我还无法完成此任务。我有以下执行程序配置:

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setWaitForTasksToCompleteOnShutdown(true);     
executor.setAwaitTerminationSeconds(30);
Run Code Online (Sandbox Code Playgroud)

我的任务基本上是这样设置的:

    myExecutor.execute(() -> {
        while(true) {
            doSomething();
        }
    });
Run Code Online (Sandbox Code Playgroud)

我假设我需要在执行程序关闭时在线程中设置一个标志,以使循环中断。还有其他推荐的方法吗?

孙兴斌*_*孙兴斌 5

您的run方法是一个无休止的循环,因此您不需要

executor.setWaitForTasksToCompleteOnShutdown(true);     
executor.setAwaitTerminationSeconds(30);
Run Code Online (Sandbox Code Playgroud)

删除上面的代码后,当您关闭线程池时,您的工作线程将立即标记为iterrupted,但它们将继续工作(除非它们正在睡眠,否则将抛出InterruptionException),并且缓存队列中的任务将不会执行。您只能检查此状态,而不必开始下一个迭代。

myExecutor.execute(() -> {
    while(true && !Thread.currentThread().isInterrupted()) {
        doSomething();
    }
});
Run Code Online (Sandbox Code Playgroud)