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

Executor service shutdownNow , how it works

根据文档的方法 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只调用工作线程的中断方法

这是内部机制,但如果你像下面这样添加try nad catch,你会从sleep方法中抛出InterruptedException(因为线程已经被shutdown方法中断)所以shutdown方法真正改变了线程状态。

 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(() -> {
        try {
            while (true) {
                Thread.sleep(1000);
                System.out.println("Done: " + Thread.currentThread().isInterrupted());
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    });
    Thread.sleep(3000);
    service.shutdownNow();
}

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