如何关闭执行器服务?

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


答案 1

典型的模式是:

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

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

例如,以下代码将打印 。但是如果你注释掉这一行,它将打印出来,因为执行器中的线程仍在运行。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...");
}

答案 2

最好的方法是我们在javadoc中实际拥有的东西,它是:

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

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();
    }
}