日期:2014-05-20 浏览次数:20838 次
public class BufferLock
{
private int value;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
value=i;
isEmpty=false;
notify();
}
public synchronized int get()
{
while(isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
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++)
{
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 Receiver get: "+buffer.get());
}
public static void main(String args[])
{
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
public class BufferLock {无论哪个线程锁了buffer,另外一个线程就只能wait了,直到noticy。也就不会出现多次receive或者多次sender的现象了。
public static void main(String args[]) {
BufferLock buffer = new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
private int value;
private boolean isEmpty = true;
public void put(int i) {
while (!isEmpty)
try {
this.wait();
} catch (InterruptedException e) {
}
value = i;
isEmpty = false;
notify();
}
public int get() {
while (isEmpty)
try {
this.wait();
} catch (InterruptedException e) {
}
isEmpty = true;
notify();
return value;
}
}
class Sender extends Thread {
private BufferLock buffer;
public Sender(BufferLock buffer) {
this.buffer = buffer;
}
public void run() {
synchronized (buffer) {
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() {
synchronized (buffer) {
for (int i = 1; i < 6; i++)
System.out.println("\t\t Receiver get: " + buffer.get());
}
}
}