public class ProducerConsumer { public static void main (String args[]) { BufferLock buffer = new BufferLock(); (new Producer(buffer)).start(); (new Consumer(buffer)).start(); }
}
class BufferLock //加互斥锁的缓冲区 { private char value; //共享变量 private boolean isEmpty=true; //value是否为空的信号量
public synchronized void put(char c) //同步方法 { while (!isEmpty) //当value不空时,等待 try { this.wait(); //使调用该方法的当前线程等待,即阻塞自己 } catch(InterruptedException e) {} value = c; //当value空时,value获得值 isEmpty = false; //设置value为不空状态 notify(); //唤醒其他等待线程 } public synchronized char get() //同步方法 { while (isEmpty) //当value空时,等待 try { this.wait(); } catch(InterruptedException e) {} isEmpty = true; //设置value为空状态,并返回值 notify(); return value; }}
class Producer extends Thread { private BufferLock buffer; char[] c ={‘a’,’b’,’c’,’d’,’e’,’f’};
public Producer(BufferLock buffer) { this.buffer = buffer; } public void run( ) { for (int i=0; i<c.length; i++) { buffer.put(c[i]); System.out.println("生产者的数据是 : "+c[i]); } }}
class Consumer extends Thread { private BufferLock buffer;
public Consumer(BufferLock buffer) { this.buffer = buffer ; } public void run() { for (int i=0; i<6; i++) System.out.println("消费者的数据是 : "+buffer.get()); }}