线程同步的问题。。
//采用信号量和同步方法使发送线程与接收线程同步运行
public class BufferLock {
/**
* @param args
*/
private int value;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!isEmpty) //当value不空时,等待
try
{
this.wait(); //使调用该方法的当前线程等待,即阻塞自己
}
catch(InterruptedException e) {}
value =i; //当value空时,value获得值
isEmpty=false; //设置value为不空状态
notify(); //唤醒其他等待线程
}
public synchronized int get()
{
while(isEmpty)
try
{
this.wait();
}
catch(InterruptedException e)
{}
isEmpty=true;
notify();
return value;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
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("Sender 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());
}
}
}
在myEclipse中运行如下:
Sender put:1
Sender put:2
Receiver get:1
Receiver get:2
Sender put:3
Sender put:4
Receiver get:3
Receiver get:4
Sender put:5
Receiver get:5为什么是这样两条两条的交替输出啊?难道不是应该相互交替的运行吗?
为什么不是这样:Sender put:1
Receiver get:1
Sender put:2
Receiver get:2
...这样的啊?