如何关闭ExecutorService? [英] How to shutdown an ExecutorService?

查看:216
本文介绍了如何关闭ExecutorService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我调用 shutdownNow() shutdown()时,它都不会关闭。我读了一些线程,其中说不能保证关闭 - 有人能为我提供一个很好的方法吗?

Whenever I call shutdownNow() or shutdown() it doesn't shut down. I read of a few threads where it said that shutting down is not guaranteed - can someone provide me a good way of doing it?

推荐答案

典型的模式是:

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

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

When calling shutdownNow, the executor will (generally) try to interrupt the threads that it manages. To make the shutdown graceful, you need to catch the interrupted exception in the threads or check the interrupted status. If you don't your threads will run forever and your executor will never be able to shutdown. This is because the interruption of threads in Java is a collaborative process (i.e. the interrupted code must do something when asked to stop, not the interrupting code).

例如,以下代码打印正常退出... 。但是如果你注释掉行 if(Thread.currentThread()。isInterrupted())break; ,它将打印仍在等待... 因为执行程序中的线程仍在运行。

For example, the following code prints Exiting normally.... But if you comment out the line if (Thread.currentThread().isInterrupted()) break;, it will print Still waiting... because the threads within the executor are still running.

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 像这样:

Alternatively, it could be written with an InterruptedException like this:

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...");
}

这篇关于如何关闭ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆