class Buffer2 //加互斥锁的缓冲区
{ private int value;
private boolean isEmpty = true; //value是否为空的信号量
synchronized void put(int i)
{ while (!isEmpty) //当value不空时,等待
{ try
{ this.wait(); //等待
}
catch(InterruptedException e)
{ System.out.println(e.getMessage());
}
}
value = i; //当value空时,value获得值
isEmpty = false; //设置value为不空状态
notify(); //唤醒其他等待线程
}
synchronized int get()
{ while (isEmpty) //当value空时,等待
{ try
{ this.wait();
}
catch(InterruptedException e)
{ System.out.println(e.getMessage());
}
}
isEmpty = true; //设置value为空状态,并返回值
notify();
return value;
}
}
class Sender2 extends Thread //发送线程
{ private Buffer2 bf;
public Sender2(Buffer2 bf)
{ this.bf = bf;
}
public void run( )
{ for (int i=1;i<6;i++)
{ bf.put( i );
System.out.println("Sender put, " + i );
}
}
public static void main (String args[])
{ Buffer2 bf = new Buffer2();
(new Sender2(bf)).start();
(new Receiver2(bf)).start();
}
}
class Receiver2 extends Thread //接受线程
{ private Buffer2 bf;
public Receiver2(Buffer2 bf)
{ this.bf = bf ;
}
public void run()
{ for (int i=1; i<6;i++)
System.out.println("\t\t Receiver get, " + bf.get()) ;
}
}
D:\myjava>javac Sender2.java
D:\myjava>java Sender2
Sender put, 1
Receiver get, 1
Sender put, 2
Receiver get, 2
Sender put, 3
Receiver get, 3
Sender put, 4
Receiver get, 4
Sender put, 5
Receiver get, 5
D:\myjava>java Sender2
Sender put, 1
Sender put, 2
Receiver get, 1
Sender put, 3
Receiver get, 2
Receiver get, 3
Sender put, 4
Receiver get, 4
Sender put, 5
Receiver get, 5
D:\myjava>java Sender2
Sender put, 1
Sender put, 2
Receiver get, 1
Sender put, 3
Receiver get, 2
Sender put, 4
Receiver get, 3
Sender put, 5
Receiver get, 4
Receiver get, 5
D:\myjava>java Sender2
Sender put, 1
Sender put, 2
Receiver get, 1
Sender put, 3
Receiver get, 2
Receiver get, 3
Sender put, 4
Receiver get, 4
Receiver get, 5
Sender put, 5
D:\myjava>java Sender2
Sender put, 1
Sender put, 2
Receiver get, 1
Sender put, 3
Receiver get, 2
Sender put, 4
Receiver get, 3
Receiver get, 4
Sender put, 5
Receiver get, 5