执行器服务shutdownNow,它如何工作

时间:2018-10-03 05:44:53

标签: 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仅调用工作线程的中断方法

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这是内部机制,但是如果您添加如下所示的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();
}
相关问题