| 本帖最后由 xibozglr 于 2013-11-29 19:07 编辑 
 生产者消费者问题,为什么t1和t2线程执行不完啊???到这晕菜了,线程是怎么循环啊??什么时候线程执行完毕啊???
 
 //描述资源
 class ZiYuan
 {
 private String name;
 private int count;
 
 //定义标记
 private boolean flag;
 
 //提供给商品赋值的方法
 public synchronized void set(String name)
 {
 if(flag)//判断标记为true,执行wait等待,为false,就生产
 
 {
 try
 {
 wait();
 }
 catch (InterruptedException e)
 {
 }
 }
 
 this.name=name+"--"+count;
 count++;
 
 System.out.println(Thread.currentThread().getName()+"生产"+this.name);
 
 //生产完毕,将标记改为true
 flag=true;
 //唤醒消费者
 notify();
 }
 
 //提供获取商品的方法
 public synchronized void get()
 {
 if(!flag)
 {
 try
 {
 wait();
 }
 catch (InterruptedException e)
 {
 }
 }
 
 System.out.println(Thread.currentThread().getName()+"消费"+this.name);
 
 //消费完毕,将标记改为false
 flag=false;
 //唤醒生产者
 notify();
 }
 }
 
 
 class ShengChanZhe implements Runnable
 {
 private ZiYuan z;
 public ShengChanZhe(ZiYuan z)
 {
 this.z=z;
 }
 
 public void run()
 {
 z.set("面包");
 }
 }
 
 
 class XiaoFeiZhe implements Runnable
 {
 private ZiYuan z;
 public XiaoFeiZhe(ZiYuan z)
 {
 this.z=z;
 }
 
 public void run()
 {
 z.get();
 }
 }
 
 
 class ShengChanXiaoFei
 {
 public static void main(String[] args)
 {
 //创建资源
 ZiYuan z=new ZiYuan();
 
 //创建两个任务
 ShengChanZhe s=new ShengChanZhe(z);
 XiaoFeiZhe x=new XiaoFeiZhe(z);
 
 //创建线程
 Thread t1=new Thread(s);
 Thread t2=new Thread(x);
 
 t1.start();
 t2.start();
 
 }
 }
 
 
 |