当executorservice shutdown()时,运行/阻塞的runnables会发生什么?

rou*_*ble 3 java multithreading design-patterns executorservice

我今天发布了一个关于线程模式的问题,几乎每个人都建议我查看ExecutorService.

当我查看ExecutorService时,我想我错过了一些东西.如果服务有运行或阻塞的线程,并且有人调用ExecutorService.shutdown(),会发生什么.正在运行或阻止的线程会发生什么?

ExecutorService在终止之前是否等待这些线程完成?

我问这个的原因是因为很久以前我曾经涉足Java时,他们弃用了Thread.stop(),我记得停止线程的正确方法是使用sempahores并在必要时扩展Thread:

public void run () {
    while (!this.exit) {
        try {
            block();
            //do something
        } catch (InterruptedException ie) {
        }
    }
}

public void stop () {
    this.exit = true;

    if (this.thread != null) {
        this.thread.interrupt();
        this.thread = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

ExecutorService如何处理正在运行的线程?

Bal*_*usC 9

来自ExecutorService#shutdown():

启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务.如果已经关闭,调用没有其他影响.

所以它会等待那些线程完成.

另一种选择是 ExecutorService#shutdownNow()

尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表.

除尽力尝试停止处理主动执行任务之外,没有任何保证.例如,典型的实现将取消via Thread.interrupt(),因此任何未能响应中断的任务可能永远不会终止.

你只需要在自己Thread#isInterrupted()while循环中聆听run().