关于生产者,消费者问题

abc44718455 2008-02-03 01:54:45
我写了个正确的生产者,消费者问题,能够运行成功:
package org.com;

public class consumer implements Runnable{
buffer bu ;
public consumer(buffer bu){
this.bu = bu;
}

public void run(){
while(true){
bu.out();
}

}

}






package org.com;

public class producer implements Runnable{
buffer bu;
String name = "";
String sex = "";


public producer(buffer bu){
this.bu = bu;
}

public void run(){
int i = 0;
while(true){
if(i == 0){
bu.put("zhangshan", "man");

}
else{
bu.put("lisi", "feman");

}
i = (i+1)%2;

}
}

}




package org.com;

public class buffer {
String name = "unknow";
String sex = "unknow";
boolean bFull = false;

public synchronized void put(String name,String sex){
if(bFull==true)
try{this.wait();}catch(Exception e){}
this.name = name;
try{Thread.sleep(1);}catch(Exception e){}
this.sex = sex;
bFull = true;
this.notify();


}

public synchronized void out(){
if(bFull==true)
try{this.wait();}catch(Exception e){}
System.out.println("name:"+name+",sex:"+sex);
bFull = false;
this.notify();

}

public static void main(String[] args){
buffer bu = new buffer();
producer pd = new producer(bu);
consumer cs = new consumer(bu);
Thread t1 = new Thread(pd);
Thread t2 = new Thread(cs);
t1.start();
t2.start();
}

}
可是当我把程序改写一下,就不能按原来的实现了,小弟不知道是什么原因,请大家指点:
package org.com;

public class buffer {
String name = "unknow";
String sex = "unknow";
boolean bFull = false;

public synchronized void put(String name,String sex){
if(bFull==false){

this.name = name;
try{Thread.sleep(1);}catch(Exception e){}
this.sex = sex;
bFull = true;
this.notify();
}else
try{this.wait();}catch(Exception e){}

}

public synchronized void out(){
if(bFull==true){

System.out.println("name:"+name+",sex:"+sex);
bFull = false;
this.notify();
}else
try{this.wait();}catch(Exception e){}

}

public static void main(String[] args){
buffer bu = new buffer();
producer pd = new producer(bu);
consumer cs = new consumer(bu);
Thread t1 = new Thread(pd);
Thread t2 = new Thread(cs);
t1.start();
t2.start();
}

}
其中标记的部分是修改的部分
...全文
173 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
老紫竹 2008-02-03
  • 打赏
  • 举报
回复
差别很大
比如put

if (bFull == true) {
try {
this.wait();
} catch (Exception e) {}
}
this.name = name; // 虽然前面在等待,但等待完毕,这句话肯定会被执行的哦


而你新改的代码,和下面这个等价,请注意
  public synchronized void put2(String name, String sex) {
if (bFull == true) {
try {
this.wait();
} catch (Exception e) {}
} else {
this.name = name; // 及时等到了,这个代码还是不会被执行的,和你前一个代码比,问题就出现在这里了!
try {
Thread.sleep(1);
} catch (Exception e) {}
this.sex = sex;
bFull = true;
this.notify();
}
}


那个 out 我就不分析了!

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧