package com.test;
public class UsingWaitAndNotify {
public static void main(String[] args) {
Cup cup = new Cup();
Thread maker = new Thread(new Maker(cup));
maker.start();
Thread washer = new Thread(new Washer(cup));
washer.start();
}
}
class Cup {
private boolean washed = false;
public synchronized void makeTea() throws InterruptedException {
System.out.println("Maker>>准备泡茶");
if (!washed) {
System.out.println("Maker>>很无奈,杯子是脏的,我只有等它被洗干净,我自己懒得动手洗");
wait();
}
System.out.println("Maker>>终于拿到干净的杯子了,开始泡一杯清茶");
}
public synchronized void washCup() throws InterruptedException {
System.out.println("Washer>>正在洗杯子");
Thread.sleep(3000);
washed = true;
notifyAll();
System.out.println("Washer>>杯子洗干净了,你可以拿去泡茶用了");
}
}
class Washer implements Runnable {
private Cup cup;
public Washer(Cup cup) {
this.cup = cup;
}
public void run() {
System.out.println(this.getClass().getSimpleName() + ">>我是清洁工,开始洗杯子");
try {
cup.washCup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Maker implements Runnable {
private Cup cup;
public Maker(Cup cup) {
this.cup = cup;
}
public void run() {
System.out.println(this.getClass().getSimpleName() + ">>我是泡茶工,我开始泡茶");
try {
cup.makeTea();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
Maker>>我是泡茶工,我开始泡茶
Washer>>我是清洁工,开始洗杯子
Maker>>准备泡茶
Maker>>很无奈,杯子是脏的,我只有等它被洗干净,我自己懒得动手洗
Washer>>正在洗杯子
Washer>>杯子洗干净了,你可以拿去泡茶用了
Maker>>终于拿到干净的杯子了,开始泡一杯清茶