我试着重复一下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
好像你打电话的时候
关闭
执行器必须中断所有线程,我必须转到catch块(catch)
InterruptedException
)但它不起作用。