package Improve;
class BufferLock
{
private int value=0;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!this.isEmpty)
{
try
{
this.wait();
}
catch(InterruptedException e){}
}
this.value=i;
this.isEmpty=false;
notify();
}
public synchronized int get()
{
while(this.isEmpty)
{
try
{
this.wait();
}
catch(InterruptedException e){}
}
this.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++)
{
this.buffer.put(i);
System.out.println("Sender put:"+i);
}
}
/**
* @param args
*/
}
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:"+this.buffer.get());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
想要得了Sender与Receiver交替的结果。
试过把synchronized扔for里面,能行。写到方法前,失败
class BufferLock
{
private int value=0;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!this.isEmpty)
{
try
{
this.wait();
}
catch(InterruptedException e){}
}
this.value=i;
this.isEmpty=false;
notify();
}
public synchronized int get()
{
while(this.isEmpty)
{
try
{
this.wait();
}
catch(InterruptedException e){}
}
this.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++)
{
this.buffer.put(i);
System.out.println("Sender put:"+i);
}
}
/**
* @param args
*/
}
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:"+this.buffer.get());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
想要得了Sender与Receiver交替的结果。
试过把synchronized扔for里面,能行。写到方法前,失败