三个和尚吃馒头

来源:互联网 发布:青岛知行国际有二反吗 编辑:程序博客网 时间:2024/04/28 08:01
 需求:三个吃饭的和尚与一个做饭的和尚 三个和尚吃馒头,
 当馒头吃光时, 通知做饭的和尚来蒸馒头,三个和尚去等待。
  馒头做好后,通知三个和尚来吃馒头,
 做饭的和尚去等待。 三个和尚吃完在做馒头
 

public class Test2 {
    public static Listguo=new ArrayList<>();
    public static voidmain(String[] args) {
       HuoFu huoFu=new HuoFu("大头和尚");
       ChiHuo chiHuo1=new ChiHuo("牛鼻子和尚");
       ChiHuo chiHuo2=new ChiHuo("白眉和尚");
       ChiHuo chiHuo3=new ChiHuo("花和尚");
       huoFu.start();
       chiHuo1.start();
       chiHuo2.start();
       chiHuo3.start();
    }
}
class ManTou{
    private int n;

    public ManTou(int n){
       this.n = n;
    }

    @Override
    public String toString(){
       return "第"+n+"个馒头";
    }
}
class HuoFu extends Thread{
    private Stringname;

    public HuoFu(Stringname) {
       this.name = name;
    }

    //做馒头
    @Override
    public void run(){
       while(true) {
          synchronized ("chi") {
              for (int i = 0; i < 30;i++) {
                 ManTou mt = new ManTou(i + 1);
                 System.out.println(name + "做好了" + mt);
                 Test2.guo.add(mt);
                 try {
                    Thread.sleep(100);
                 } catch (InterruptedException e) {
                    e.printStackTrace();
                 }
              }
             System.out.println(name+"说:馒头都做好了,大家醒来吃吧");
              "chi".notifyAll();

           }
         synchronized ("zheng") {
             try {
                System.out.println("我去睡一会");
                "zheng".wait();
             } catch (InterruptedExceptione) {
                e.printStackTrace();
             }
          }
       }

    }
}
class ChiHuo extends Thread{
    public ChiHuo(Stringname) {
       this.name = name;
    }

    private Stringname;
    //吃馒头
    @Override
    public void run(){
      while(true) {
         synchronized ("chi") {
             if (Test2.guo.size() == 0){
                System.out.println(name +"说:馒头还没做好,我先去睡一会");
                try {
                   System.out.println(name+"说:我睡前可是通知了伙夫做馒头呀");
                    synchronized ("zheng"){
                        "zheng".notify();

                     }
                   "chi".wait();
                } catch (InterruptedException e) {
                   e.printStackTrace();
                }

             }
             else {
                ManTou mt = Test2.guo.remove(0);
                System.out.println(name + "吃掉了" + mt);
             }
          }
          long n =(long) (Math.random() * 5 + 1) * 1000;
          try {
             Thread.sleep(n);
          } catch(InterruptedException e) {
             e.printStackTrace();
          }
      }

    }
}

原创粉丝点击