您的位置:首页 > 其它

三个和尚吃馒头

2017-05-29 13:41 225 查看
 需求:三个吃饭的和尚与一个做饭的和尚 三个和尚吃馒头,
 当馒头吃光时, 通知做饭的和尚来蒸馒头,三个和尚去等待。
  馒头做好后,通知三个和尚来吃馒头,
 做饭的和尚去等待。 三个和尚吃完在做馒头
 

public class Test2 {
    public static List
guo=new ArrayList<>();
    public static void
main(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 String
name;

    public HuoFu(String
name) {
     
  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 (InterruptedException
e) {
     
     
     
 e.printStackTrace();
     
     
   }
     
     }
     
  }

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

    private String
name;
    //吃馒头
    @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();
     
     }
     
 }

    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: