java 通知与等待 问题

来源:百度知道 编辑:UC知道 时间:2024/06/09 13:20:11
class Goods
{
private int goodsNo;
private boolean available=false;
public synchronized int receive()
{
while(available==false)
{
try
{
wait();
}catch(InterruptedException e){}
}
available=false;
notifyAll();
return goodsNo;
}
public synchronized void send(int goodsNo)
{
while(available==true)
{
try
{
wait();
}catch(InterruptedException e){}
}
this.goodsNo=goodsNo;
available=true;
notifyAll();

}
}
class Sender extends Thread
{
private Goods goods;
private int number;
public Sender(Goods g,int n)
{
goods=g;
number=n;
}
public void run()
{
for(int i=0;i <10;i++)
{
goods.send(i);
System.out.println("发送人"+number+"送出"+i);
try{
sleep((int)(Math.random()*100));
}catch(InterruptedEx

sleep和wait的区别有:
1,这两个方法来自不同的类分别是Thread和Object
2,最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法。
3,wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在
任何地方使用
synchronized(x){
x.notify()
//或者wait()
}
4,sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常