50

每当我打电话shutdownNow()shutdown()它不会关闭。我读过一些帖子说不能保证关闭 - 有人可以为我提供一个好的方法吗?

4

2 回答 2

91

典型的模式是:

executorService.shutdownNow();
executorService.awaitTermination();

调用shutdownNow时,执行程序(通常)会尝试中断它管理的线程。要使关闭优雅,您需要在线程中捕获中断的异常或检查中断状态。如果您不这样做,您的线程将永远运行,您的执行程序将永远无法关闭。这是因为Java 中线程的中断是一个协作过程(即被中断的代码在被要求停止时必须做某事,而不是中断的代码)。

例如,以下代码打印Exiting normally.... 但是,如果您注释掉该行if (Thread.currentThread().isInterrupted()) break;,它将打印Still waiting...,因为执行程序中的线程仍在运行。

public static void main(String args[]) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(new Runnable() {

        @Override
        public void run() {
            while (true) {
                if (Thread.currentThread().isInterrupted()) break;
            }
        }
    });

    executor.shutdownNow();
    if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) {
        System.out.println("Still waiting...");
        System.exit(0);
    }
    System.out.println("Exiting normally...");
}

或者,它可以这样写InterruptedException

public static void main(String args[]) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(new Runnable() {

        @Override
        public void run() {
            try {
                while (true) {Thread.sleep(10);}
            } catch (InterruptedException e) {
                //ok let's get out of here
            }
        }
    });

    executor.shutdownNow();
    if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) {
        System.out.println("Still waiting...");
        System.exit(0);
    }
    System.out.println("Exiting normally...");
}
于 2012-05-08T18:41:03.317 回答
31

最好的方法是我们在 javadoc 中实际拥有的内容:

以下方法分两个阶段关闭ExecutorService,首先调用shutdown以拒绝传入的任务,然后 shutdownNow在必要时调用 取消任何延迟的任务:

void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(60, TimeUnit.SECONDS))
                System.err.println("Pool did not terminate");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}
于 2016-05-25T17:22:46.457 回答