我有一个每天执行多个线程的要求。每个线程都执行一些任务。我试图解决的问题是是否使用作为参数传递的停止文件来优雅地终止执行程序服务。
我正在使用在线程的 run 方法中检查 stopfile 的方法,但它将对所有剩余任务执行空运行。相反,我寻找一种方法来停止执行器服务本身中的任务。有没有办法做到这一点。
我正在看这篇文章:Removing all queued tasks of an ThreadPoolExecutor
有人可以对此进行更多扩展吗?
最佳答案
I am using the approach of checking the stopfile in the thread's run method, but it will do an empty run for all the remaining tasks. Instead I looking for a way to stop the tasks in the executorservice itself. Is there a way to do that.
我认为停止 ExecutorService
的正确方法是使用 executorservice.shutdownNow();
方法。这将取消所有尚未运行的作业并中断所有正在运行的线程。
要测试中断,您的任务应该执行以下操作:
while (!Thread.currentThread().isInterrupted()) {
...
}
在任何地方捕获 InterruptedException
,都需要确保重新启用中断标志:
try {
// something that throws InterruptedException
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// maybe we should quit the thread here
}
如果您使用的第三方库可能会引发InterruptedException
,那么您可能必须使用executorservice.shutdown()
来取消作业,但是不中断线程。然后,您应该共享某种 volatile boolean 关闭
标志(或AtomicBoolean
)并在您的运行方法中执行某些操作:
while (!Thread.currentThread().isInterrupted() && !shutdown) {
...
}
顺便说一句,你提到了“线程的运行方法”。可以肯定的是,您应该实现 Runnable 并将其提交给 ExecutorService。您不应提交 Thread
实例。
关于java - 如何使用 stopfile 方法优雅地停止 executorservice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18904762/