java - 执行服务 shutdownNow ,它是如何工作的

标签 java concurrency executorservice

根据方法 shutdownNow (ExecutorService) 的文档

There are no guarantees beyond best-effort attempts to stop
      processing actively executing tasks.  For example, typical
      implementations will cancel via {@link Thread#interrupt}, so any
      task that fails to respond to interrupts may never terminate

我有以下代码:

public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor(r -> {
            final Thread thread = new Thread(r);
            thread.setDaemon(false);
            return thread;
        });
        service.submit(() -> {
            while (true) {
                Thread.sleep(1000);
                System.out.println("Done: " + Thread.currentThread().isInterrupted());
            }
        });
        Thread.sleep(3000);
        service.shutdownNow();
    }

这是输出:

Done: false
Done: false

两个循环后停止执行。 shutdownNow 如何中断我的工作,我只有无限循环,没有检查 Thread.currentThread.isInterrupted();

在我看来,shutdownNow只调用工作线程的中断方法

最佳答案

Thread.sleep() 检查 .isInterrupted() 并在被中断时抛出 InterruptedException。您的 lambda 隐式地 throws InterruptedException,因此当执行程序关闭时它永远不会到达您的 System.out.println。您可以浏览source for ThreadPoolExecutor看看这是怎么发生的。

关于java - 执行服务 shutdownNow ,它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620399/

相关文章:

java - 我通常如何添加 userprofile 变量 %userprofile%

c++ - concurrency::parallel_sort 开销和性能影响(经验法则)?

java - 在 Tomcat 容器中运行的 Web 应用程序是否需要关闭 ExecutorService?

java - 为什么我的图像不显示在 jsp 中? [使困惑]

java - 函数执行良好,没有错误,但没有返回预期的响应

c++ - 使用 Async/Futures 并行和并发地计算 vector 的范数

php - 可以同时执行两个或多个查询吗?

java - Spring Boot 和执行器服务

java - ExecutorService - 主线程关闭

java - 异常: Key Down/Up events only make sense for modifier keys