日期:2014-05-20 浏览次数:20797 次
public class BufferLock {
private int value;
private boolean isEmpty = true;
public synchronized void put(int i){
while (!isEmpty) {//当value不空时,等待
try {
this.wait();
} catch (InterruptedException e) {
}
}
this.value = i;
isEmpty = false;
notify();
}
public synchronized int get(){
while(isEmpty){//当value为空时,等待
try {
this.wait();
} catch (InterruptedException e) {
}
}
isEmpty = true;
notify();
return value;
}
public static void main(String[] args) {
BufferLock buffer = new BufferLock();
(new Sender2(buffer)).start();
(new Receiver2(buffer)).start();
}
}
class Sender2 extends Thread{
private BufferLock buffer;
public Sender2(BufferLock buffer){
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i < 6; i++) {
buffer.put(i);
System.out.println("Sender put" + i);
try {
sleep(1);
} catch (InterruptedException e) {}
}
}
}
class Receiver2 extends Thread{
private BufferLock buffer;
public Receiver2(BufferLock buffer){
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i < 6; i++) {
System.out.println("\t\t Receiver get: " + buffer.get());
try {
sleep(1);
} catch (InterruptedException e) {}
}
}
}
Sender put1
Receiver get: 1
Sender put2
Receiver get: 2
Sender put3
Receiver get: 3
Sender put4
Receiver get: 4
Receiver get: 5
Sender put5
public class BufferLock
{
private int value;
private boolean isEmpty = true;
public synchronized void put(int i)
{
while (!isEmpty)
{// 当value不空时,等待
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.value = i;
System.out.println("Sender put" + i);
isEmpty = false;
notify();
}
public synchronized int get()
{
while (isEmpty)
{// 当value为空时,等待
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
isEmpty = true;
System.out.println("\t\t Receiver get: " + value);
notify();
return value;
}
public static void main(String[] args)
{
BufferLock buffer = new BufferLock();
(new Sender2(buffer)).start();
(new Receiver2(buffer)).start();
}
}
class Sender2 extends Thread
{
private BufferLock buffer;
public Sender2(BufferLock buffer)
{
this.buffer = buffer;
}
@Override
public void run()
{
for (int i = 1; i < 6; i++)
{
buffer.put(i);
try
{
sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Receiver2 extends Thread
{
private BufferLock buffer;
public Receiver2(BufferLock buffer)
{
this.buffer = buffer;
}
@Override
public void run()
{
for (int i = 1; i < 6; i++)
{
buffer.get();
try
{
sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
sleep(100);就会看到效果