问题: Baozipu类和Chihuo类都创建了Baozi的对象为什么main方法还要传个Baozi的对象参数进去呢?这里有点不解 难道是因为锁? package cn.XianCheng; public class Baozipu extends Thread{ //创建一个包子类型的变量 Baozi bz = new Baozi(); //使用带参构造方法为这个包子赋值 public Baozipu(Baozi cz){ this.bz = cz ; } //设置线程任务生产包子 @Override public void run() { while(true){ //必须使用同步技术保证只有一个线程在执行 这里用 同步代码块 synchronized(bz){ //判断有没有包子 if(bz.flag==true){ //有包子包子铺就进入等待状态 bz.notify(); try { bz.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if(bz.flag==false){ //没有包子就生产包子 bz.pi = "薄皮"; bz.xian = "牛肉馅"; System.out.println("正在生产包子"+Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bz.flag = true; System.out.println("包子铺已经生产好了:"+bz.pi+bz.xian+"包子"+Thread.currentThread().getName()); bz.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
-------------------------------------------------------------------------------------------------------------
package cn.XianCheng; public class Chihuo extends Thread{ Baozi bz = new Baozi(); public Chihuo(Baozi cz){ this.bz = cz ; } @Override public void run() { while(true){ synchronized (bz){ if(bz.flag == false){ bz.notify(); try { bz.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if(bz.flag == true){ System.out.println("正在吃:"+bz.pi+bz.xian+"包子"+Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bz.flag = false ; System.out.println("吃完了"+Thread.currentThread().getName()); System.out.println("-------------------------------------"); bz.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
--------------------------------------------------------------------------------------------------
package cn.XianCheng; public class Baozi { //皮 //馅 //包子的状态 String pi; String xian; boolean flag = false; }
--------------------------------------------------------------------------------------------------
package cn.XianCheng; public class XianChengmain { public static void main(String[] args) { Baozi cz = new Baozi();//创建包子对象 new Baozipu(cz).start();//开启包子铺线程 new Chihuo(cz).start();//开启吃货线程 } }
pardon110
相关分类