package practice;
/*
* 6、
老媽想喝茶曲聂,喝茶需要有茶具和茶葉霹购,家里沒有就需要兩個兒子,
各自去買朋腋,買的東西不一樣齐疙,花費時間不一樣,例如旭咽,老大去買茶葉需要10分鐘贞奋,
老二去買茶具需要8分鐘,一起出的門穷绵,老二回來時轿塔,老媽依舊不能如愿喝茶,
只有當兩個兒子都回到家時,才能如愿煮水泡茶喝
*/
public class TeaTest {
public static void main(String[] args) {
Desk desk = new Desk();
Mother m = new Mother(desk);
m.start();
}
}
class Mother extends Thread {
private Desk desk;
public Mother(Desk desk) {
this.desk = desk;
}
public void run() {
System.out.println("想喝茶");
synchronized (desk) {
if (desk.getCup() == 0) {
System.out.println("想喝茶勾缭,沒茶杯洽议,mike去買");
Mike mike = new Mike(desk);
mike.start();
}
if (desk.getTea() == 0) {
System.out.println("想喝茶,沒茶葉漫拭,tom去買");
Tom tom = new Tom(desk);
tom.start();
}
while(desk.getTea() == 0||desk.getCup() == 0) {
try {
desk.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("可以喝茶");
}
}
}
class Mike extends Thread {
private Desk desk;
public Mike(Desk desk) {
this.desk = desk;
}
public void run() {
System.out.println("我是mike,老媽叫我買茶杯");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
desk.setCup(1);
}
}
class Tom extends Thread {
private Desk desk;
public Tom(Desk desk) {
this.desk = desk;
}
public void run() {
System.out.println("我是tom,老媽叫我買茶葉");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
desk.setTea(1);
}
}
class Desk extends Thread {
private int cup = 0;
private int tea = 0;
public? int getTea() {
return tea;
}
public int getCup() {
return cup;
}
public synchronized void setCup(int cup) {
this.cup = cup;
this.notify();
System.out.println("我是mike亚兄,茶杯買回來了,叫醒老媽");
}
public synchronized void setTea(int tea) {
this.tea = tea;
this.notify();
System.out.println("我是tom 采驻,茶葉買回來了审胚,叫醒老媽");
}
}