执行程序服务关闭不中断线程



我尝试重复Bruce Eckel的书"在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 block(catchInterruptedException(,但它不起作用。

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

ThreadPoolExecutor.shutdown

启动有序关机,其中以前提交的任务是 已执行,但不接受任何新任务。

ThreadPoolExecutor.shutdownNow

此实现通过 Thread.interrupt(( 中断任务

因此,您可以改用shutdownNow

最新更新