packageThread.Wait;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.TimeUnit;classCar {private boolean waxOn = false;//上蜡
public synchronized voidwaxed() {
waxOn= true;
notifyAll();
}//抛光
public synchronized voidbuffed() {
waxOn= false;
notifyAll();
}public synchronized void waitForWaxing() throwsInterruptedException {while (waxOn == false)
wait();
}public synchronized void waitForBuffing() throwsInterruptedException {while (waxOn == true)
wait();
}
}class WaxOn implementsRunnable {privateCar car;publicWaxOn(Car c) {
car=c;
}
@Overridepublic voidrun() {try{while (!Thread.interrupted()) {
System.out.println("Wax On!");
TimeUnit.MILLISECONDS.sleep(200);
car.waxed();//上完蜡 waxOn = true;notifyAll();
car.waitForBuffing();//等待抛光while (waxOn == true) wait();
}
}catch(Exception e) {
System.out.println("Exiting via interrupt");
}
System.out.println("Ending Wax On task");
}
}class WaxOff implementsRunnable {privateCar car;publicWaxOff(Car c) {
car=c;
}
@Overridepublic voidrun() {try{while (!Thread.interrupted()) {
car.waitForWaxing();//等待上蜡 while (waxOn == false) wait();
System.out.println("Wax Off!");
TimeUnit.MILLISECONDS.sleep(200);
car.buffed();//已经抛光 waxOn = false; notifyAll();
}
}catch(Exception e) {
System.out.println("Exiting via interrupt");
}
System.out.println("Ending Wax Off task");
}
}public classWaxOMatic {public static void main(String[] args) throwsException {
Car car= newCar();
ExecutorService exec=Executors.newCachedThreadPool();
exec.execute(newWaxOff(car));
exec.execute(newWaxOn(car));
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();
}
}