代码之家  ›  专栏  ›  技术社区  ›  Almas Abdrazak

执行器服务现在关闭,如何工作

  •  2
  • Almas Abdrazak  · 技术社区  · 7 年前

    根据方法文件 shutdownNow (执行人服务)

    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
    

    在两个循环之后,停止执行。 关机是怎么打断我的工作的,我只是有无限的循环,没有检查 Thread.currentThread.isInterrupted();

    在我心中, 现在关闭 只调用工作线程的中断方法

    2 回复  |  直到 7 年前
        1
  •  2
  •   dimo414    7 年前

    Thread.sleep() 检查 .isInterrupted() 扔一个 InterruptedException 如果被打断了。您的lambda隐式 throws InterruptedException 所以它永远不会到达你的 System.out.println 当执行器关闭时。您可以浏览 source for ThreadPoolExecutor 看看这是怎么发生的。

        2
  •  0
  •   niemar    7 年前

    这是一种内部机制,但是如果您像下面这样添加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();
    }