读书人

又撞礁了高人来看看

发布时间: 2013-02-17 10:44:46 作者: rapoo

又触礁了,高人来看看!

class Producer implements Runnable
{
P q=null;

public Producer(P q)
{
this.q=q;
}


public void run()
{
int i=0;

while(true)
{
if(i==0)
{
q.set("Zhang San","Male");
}
else
{
q.set("Meimei","Female");
}
i=(i+1)%2;
}


}


}

class P
{


private String name="meimei";
private String sex="female";

boolean bFull=false;


public synchronized void set(String name,String sex)
{
if(bFull)
{
try
{wait();}
catch(Exception e)
{}

this.name=name;

try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.print(e.getMessage());
}

this.sex=sex;

bFull=true;


notify();

}

}




public synchronized void get()
{
if(!bFull)
{
try{
wait();
}
catch(InterruptedException e)
{ }

}

System.out.println(this.name+"---->"+this.sex);
bFull=false;

notify();

}


}


class Consumer implements Runnable
{
P q;

public Consumer(P q)
{
this.q=q;
}

public void run()
{
while(true)
{
q.get();
}

}


}


public class ThreadCommun
{
public static void main(String []args)
{
P q=new P();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();

}
}


本来是为了线程之间通讯以便 生产者和消费者 可以同步,即生产者生产一个,消费者就取走一个

但是现在一运行就一直在等待,没任何反应了,只有光标在闪
------解决方案--------------------


逻辑错了。。 if(!bFull) if(bFull) 应该反过来
[解决办法]


[解决办法]

public synchronized void set(String name,String sex)
{
if(bFull)
{
try
{wait();}
catch(Exception e)
{}
}//if 在着结束.bFull为假时,应该执行。
this.name=name;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
this.sex=sex;
bFull=true;
notify();
}

[解决办法]
把set方法中notify();后面的}放到
if(bFull)
{
try
{wait();}
catch(Exception e)
{}
后面就是你想要的结果了

读书人网 >J2SE开发

热点推荐