标题: 生产消费的线程问题,想了一下午了,有达人解惑么? [打印本页] 作者: tmac1999 时间: 2015-3-11 16:59 标题: 生产消费的线程问题,想了一下午了,有达人解惑么? public class InputOutputDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
res1 r = new res1();
new Thread(new Input1(r)).start();
new Thread(new Output1(r)).start();
}
}
class res1{
private String name;
private String sex;
private Boolean flag = false;
public synchronized void in(String name,String sex){
if(!flag){
this.name = name;
this.sex = sex;
flag = true;
notify();
}else{//检查了很久发现是此套了一个else 导致程序错误,有没有人知道 为什么这里加个else 就不行?
try{
wait();
}catch(Exception e){
System.out.println(e.toString());
}
}
}
public synchronized void out(){
if(flag){
System.out.println(this.name+".........."+this.sex);
flag = false;
notify();
}else{
try{
wait();
}catch(Exception e){
System.out.println(e.toString());
}
}
}
}
class Input1 implements Runnable{
private res1 r;
Input1(res1 r){
this.r = r;
}
int i = 0;
public void run(){
while(true){
if(i==0){
r.in("lily", "female");
}else{
r.in("孙", "男");
}
i = (i+1)%2;
}
}
}