java吧 关注:1,235,214贴子:12,702,291
  • 4回复贴,共1

渣新拜吧+提问求解

取消只看楼主收藏回复

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里面,能行。写到方法前,失败


IP属地:湖北来自手机贴吧1楼2014-02-11 00:14回复
    再次求解


    IP属地:湖北来自手机贴吧2楼2014-02-11 10:13
    回复
      求大神啊


      IP属地:湖北来自手机贴吧3楼2014-02-11 10:42
      回复


        IP属地:湖北来自百度输入法6楼2014-02-11 19:53
        回复


          IP属地:湖北来自百度输入法7楼2014-02-11 19:54
          收起回复