ExecutorService 关闭不中断线程

ExecutorService shutdown not interrupt threads

我尝试重复 Bruce Eckel 书中的例子 "thinking in java":

    public class Car {
        private boolean waxOn = false;

        public synchronized void waxed() {
            waxOn = true;
            notifyAll();
        }

        public synchronized void buffed(){
            waxOn = false;
            notifyAll();
        }

        public synchronized void waitForWaxing() throws InterruptedException {
            while (!waxOn)
                wait();
        }

        public synchronized void waitForBuffing() throws InterruptedException {
            while (waxOn)
                wait();
        }
    }

public class WaxOff implements Runnable {
    private Car car;

    public WaxOff(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("wax off!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();
                car.waitForWaxing();
            }
        } catch (InterruptedException e) {
            System.out.println("Exit via interrupt");
        }
        System.out.println("Ending Wax Off task");
    }
}

public class WaxOn implements Runnable {
    private Car car;

    public WaxOn(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("wax on!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();
                car.waitForBuffing();
            }
        } catch (InterruptedException e) {
            System.out.println("Exit via interrupt");
        }
        System.out.println("Ending Wax On task");
    }
}

public class WaxOMatic {
    public static void main(String[] args) throws Exception {
        Car car = new Car();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new WaxOff(car));
        executorService.execute(new WaxOn(car));
        TimeUnit.SECONDS.sleep(5);
        executorService.shutdown();
    }
}

但我有 不正确的 ExecutorService 行为。当我调用 shutdown 方法时,线程不会中断并继续工作。

但是如果我改变这个例子并使用

Future<?> submit = executorService.submit(new WaxOff(car));

并在延迟调用后 submit.cancel(true) - 线程中断正常。

似乎当你调用 shutdown 时,执行程序必须中断所有线程,我必须去捕获块(catch InterruptedException) 但它不起作用。

Executors.newCachedThreadPool 在内部使用 ThreadPoolExecutor 作为线程池。

ThreadPoolExecutor.shutdown:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

ThreadPoolExecutor.shutdownNow:

This implementation interrupts tasks via Thread.interrupt()

因此您可以使用 shutdownNow