public class Exercise23 {
public static void main(String[] args) throws Exception {
Car car = new Car();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new WaxOff(car));
exec.execute(new WaxOn(car));
TimeUnit.SECONDS.sleep(1); // Run for a while...
exec.shutdownNow(); // Interrupt all tasks
}
static class Car {
// 是否抛光(先抛光后上蜡)
private boolean isBuffed = false;
public synchronized void wax() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100); // 模拟 上蜡过程.
isBuffed = false; // 上蜡后,更改状态为 未抛光状态. (重新执行 抛光->上蜡过程)
notify(); // 唤醒所有等待抛光线程.
System.out.println("\nwax(): 上蜡结束, 唤醒所有等待抛光的线程");
}
public synchronized void buff() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100); // 模拟 抛光过程.
isBuffed = true; // 抛光后,更改状态 为 已抛光状态.
notify(); // 唤醒所有等待上蜡线程.
System.out.println("\nbuff(): 抛光结束, 唤醒所有等待上蜡的线程");
}
public synchronized void waitForWaxing() throws InterruptedException {
System.out.println("waitForWaxing(): 等待上蜡.");
while (isBuffed == false) // 抛光没有完成,无法上蜡 , 等待.(先抛光后上蜡)
wait();
}
public synchronized void waitForBuffing() throws InterruptedException {
System.out.println("waitForBuffing(): 等待抛光.");
while (isBuffed == true) // 上蜡没有完成, 无法抛光(先抛光后上蜡)
wait();
}
}
// 上蜡任务
static class WaxOn implements Runnable {
private Car car;
public WaxOn(Car c) {
car = c;
}
public void run() {
try {
while (!Thread.interrupted()) {
car.waitForWaxing(); // 等待上蜡.
car.wax(); // 上蜡完毕.
}
} catch (InterruptedException e) {
print("Exiting via interrupt");
}
print("Ending Wax On task");
}
}
// 上蜡结束后,开启抛光任务
static class WaxOff implements Runnable {
private Car car;
public WaxOff(Car c) {
car = c;
}
public void run() {
try {
while (!Thread.interrupted()) {
car.waitForBuffing(); // 等待抛光.
car.buff(); // 抛光完毕.
}
} catch (InterruptedException e) {
print("Exiting via interrupt");
}
print("Ending Wax Off task");
}
}
}
// 打印结果
waitForBuffing(): 等待抛光.
buff(): 抛光结束, 唤醒所有等待上蜡的线程
waitForWaxing(): 等待上蜡.
wax(): 上蜡结束, 唤醒所有等待抛光的线程
waitForBuffing(): 等待抛光.
buff(): 抛光结束, 唤醒所有等待上蜡的线程
waitForBuffing(): 等待抛光.
waitForWaxing(): 等待上蜡.
wax(): 上蜡结束, 唤醒所有等待抛光的线程
buff(): 抛光结束, 唤醒所有等待上蜡的线程
waitForBuffing(): 等待抛光.
waitForWaxing(): 等待上蜡.
wax(): 上蜡结束, 唤醒所有等待抛光的线程
waitForWaxing(): 等待上蜡.
buff(): 抛光结束, 唤醒所有等待上蜡的线程
waitForBuffing(): 等待抛光.
wax(): 上蜡结束, 唤醒所有等待抛光的线程
waitForWaxing(): 等待上蜡.
buff(): 抛光结束, 唤醒所有等待上蜡的线程
waitForBuffing(): 等待抛光.
Exiting via interrupt
Ending Wax On task
Exiting via interrupt
Ending Wax Off task