美文网首页
老师布置的奇葩作业(喝茶问题)

老师布置的奇葩作业(喝茶问题)

作者: 乱世佳人i | 来源:发表于2016-08-30 11:35 被阅读0次

    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 ,茶叶买回来了,叫醒老妈");

    }

    }

    相关文章

      网友评论

          本文标题:老师布置的奇葩作业(喝茶问题)

          本文链接:https://www.haomeiwen.com/subject/ikvfettx.html