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(); } } }