package concurrency; public class QueueBuffer { private final int SIZE; private int count = 0; private int[] buffer; public QueueBuffer(int size){ this.SIZE = size; buffer = new int[SIZE]; } public int getSIZE(){ return SIZE; } public synchronized void put(int value){ while (count == SIZE){ //buffer已经满了 等待get ,用while使用于多个生产者的状况 try { wait(); }catch (InterruptedException e){ e.printStackTrace(); } } notifyAll(); //说明buffer中有元素 能够取 buffer[count++] = value; System.out.println("Put "+value+" current size = "+count); } public synchronized int get(){ while(count == 0){//用while使用于多个消费者的状况。 try { wait();//buffer为空,须要等到put进元素 }catch (InterruptedException e){ e.printStackTrace(); } } // notify() 只是去通知其余的线程,可是synchronized 方法里面的代码仍是会执行完毕的。 // synchronized方法原本就加了锁。代码的执行跟你的notify()也无关,代码的执行是跟你的 // synchronized绑定一块儿而已。 notifyAll(); //说明刚刚从buffer中取出了元素 有空位能够加进新的元素 int result = buffer[--count]; System.out.println("Get "+result+" current size = "+count); return result; } } class Test{ public static void main(String[] args){ QueueBuffer q = new QueueBuffer(10); new Producer(q); new Producer(q); new Producer(q); new Consumer(q); new Consumer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }
Producerjava
package concurrency; import java.util.Random; public class Producer implements Runnable { Random rand = new Random(47); private QueueBuffer q; Producer(QueueBuffer q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { while (true) { q.put(rand.nextInt(q.getSIZE())); Thread.yield(); } } }
Consumer设计模式
package concurrency; public class Consumer implements Runnable { private QueueBuffer q; Consumer(QueueBuffer q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while (true){ q.get(); Thread.yield(); } } }