生产者与消费者——厨师和消费者之间的问题

厨师作为生产者,每做一道菜,消费者就消灭一道菜;dish作为一个共有属性

public class Cooker implements Runnable {
  private String name;
  private Dish d;
  private String food;
  public String [] foods = new String [] {"红烧鲫鱼","红烧肉","小炒牛肉","小白菜","番茄炒蛋","火锅","米饭"};

  public Cooker(String name, Dish d) {
    this.d = d;
    this.name = name;
  }

  public void run() {
    cook();
  }

  public void cook() {
    synchronized(d) {
      for(int i = 0; i < 10; i++) {
        Random random = new Random();
        food = foods[random.nextInt(foods.length)];
        d.setFood(food);
        if(d.isEmpty()) { //d.isEmpty为true,即盘子为空,则进入
          d.setEmpty(false);
          System.out.println(name + "烹饪了美食:" + food);
          d.notify();
          try {
            d.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }else {
          try {
            d.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}

 

public class Dish {
  private String food;
  private boolean isEmpty = true;

  public String getFood() {
    return food;
  }

  public void setFood(String food) {
    this.food = food;
  }

  public boolean isEmpty() {
    return isEmpty;
  }

  public void setEmpty(boolean isEmpty) {
    this.isEmpty = isEmpty;
  }
}

 

public class Customer implements Runnable {
  private String name;
  private Dish d;

  public Customer(String name, Dish d) {
    this.name = name;
    this.d = d;
  }

  public void run() {
    eat();
  }

  public void eat() {
    synchronized(d) {
      while(true) {
        if(!d.isEmpty()) {      //d.isEmpty为false,即盘子不为空,则进入
          d.setEmpty(true);
          System.out.println(name + "享用了美食:" + d.getFood());
          d.notify();
          try {
            d.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }else {
          try {
            d.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public Dish getD() {
    return d;
  }

  public void setD(Dish d) {
    this.d = d;
  }
}

 

public class TestProducerAndCustomer {
  public static void main(String [] args) {
    Dish d = new Dish();
    Cooker ck = new Cooker("老王",d);
    Customer cm = new Customer("小太阳",d);

    Thread tck = new Thread(ck);
    Thread tcm = new Thread(cm);

    tck.start();
    tcm.setDaemon(true);
    tcm.start();
  }
}

posted on 2018-03-09 23:11  00011101  阅读(153)  评论(0编辑  收藏  举报