关于生产者,消费者问题
我写了个正确的生产者,消费者问题,能够运行成功:
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();
}
}
其中标记的部分是修改的部分