[java]线程(三)

2014-11-24 09:09:53 · 作者: · 浏览: 1
t i = 1; i <= 5;i++){
synchronized (this) {//wait notify 必须放入同步块
while(flag){//while循环 而不是if 存在虚假唤醒
try {
this.wait();//wait方法会释放钥匙
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*制造食物*/
theva lue = new Random().nextInt(10000);
System.out.println("send the value is:"+theva lue);
/*让自己进入阻塞*/
flag = true;
/*唤醒该对象上其它等待线程*/
this.notify();
}
}
}

}
/*生产者线程和消费者线程 的等待和唤醒必须通过同一个对象
* 同步块必须使用同一个锁同一把钥匙
*/
class WaitRec implements Runnable{
WaitSend send;
public WaitRec(WaitSend send){
this.send = send;
}
@Override
public void run() {
while(true){
synchronized (send) {
while(!send.flag){
try {
send.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*消费食物*/
System.out.println("receiver theva lue is:"+send.theva lue);
/*自己进入阻塞状态*/
send.flag = false;
/*唤醒生产者*/
send.notify();

}
}
}
}