java - 如何使用 stopfile 方法优雅地停止 executorservice

标签 java multithreading executorservice

我有一个每天执行多个线程的要求。每个线程都执行一些任务。我试图解决的问题是是否使用作为参数传递的停止文件来优雅地终止执行程序服务。

我正在使用在线程的 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/

相关文章:

python - 对for循环内的python子进程感到困惑

python : Running function in thread does not modify current_thread()

java - 如何运行多个 ExecutorServices 来发出请求并通过单个接口(interface)汇集响应?

multithreading - 如何在 groovy 中使用多线程访问 1000 个端点?

Java 从 ExecutorService 设置回调

java - 如何检查Android应用程序是否进入前台?

java - Docker 中的 Postgres 服务器无法连接到 Spring Boot 应用程序

java - 素面 : submit after succes action

java - 自定义协议(protocol)处理程序未在 OSX 上传递参数

java - 为什么 Thread.stop 在 Thread.interrupt 不起作用的情况下不起作用?