线程同步出错的
采用信号量和同步方法使得发送线程和接收线程同步运行public class BufferLock {
private int value;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
value=i;
isEmpty=false;
notify();
}
public synchronized int get()
{
while(isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
isEmpty=true;
notify();
return value;
}
}
class Sender extends Thread
{
private BufferLock buffer;
public Sender(BufferLock buffer)
{
this.buffer=buffer;
}
public void run()
{
for(int i=1;i<6;i++)
{
buffer.put(i);
System.out.println("Send put:"+i);
}
}
}
class Receiver extends Thread
{
private BufferLock buffer;
public Receiver(BufferLock buffer)
{
this.buffer=buffer;
}
public void run()
{
for(int i=1;i<6;i++)
{
System.out.println("\t\t\tReceiver get:"+buffer.get());
}
}
public static void main(String args[])
{
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
但是最后运行的结果还是随机的,总是不能同步,到底是什么原因想不明白
ps:程序是书上的,用的是 eclipse[local]1[/local]