package com.subject01; import java.util.PriorityQueue; /** * 通過wait和notify 實現 * 生產者-消費者模型:當隊列滿時,生產者需要等待隊列有空間才能繼續往里面放入商品,而在等待的期間內, * 生產者必須釋放對臨界資源(即隊列)的占用權。因為生產者如果不釋放對臨界資源的占用權, * 那么消費者就無法消費隊列中的商品,就不會讓隊列有空間,那么生產者就會一直無限等待下去。 * 因此,一般情況下,當隊列滿時,會讓生產者交出對臨界資源的占用權,並進入掛起狀態。 * 然后等待消費者消費了商品,然后消費者通知生產者隊列有空間了。 * 同樣地,當隊列空時,消費者也必須等待,等待生產者通知它隊列中有商品了。這種互相通信的過程就是線程間的協作。 * com.subject01.CusAndPro.java * @author 孫濤 * 2016年5月10日 */ public class CusAndPro { private int queueSize = 10 ; private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize); public static void main(String[] args) { CusAndPro cap = new CusAndPro(); Consumer cus = cap.new Consumer(); Producer pro = cap.new Producer(); Thread cusT = new Thread(cus); Thread proT = new Thread(pro); proT.start(); cusT.start(); } /** * 消費者 * com.subject01.CusAndPro.java * @author 孫濤 * 2016年5月10日 */ class Consumer implements Runnable{ @Override public void run() { cousume(); } private void cousume() { while(true){ synchronized (queue) { while(queue.size() ==0){ try { System.out.println("隊列空,等待數據。。。"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); queue.notify(); } } queue.poll() ; queue.notify(); System.out.println("從隊列中取走一個元素,隊列中剩余"+queue.size()+"個"); } } } } /** * 生產者 * com.subject01.CusAndPro.java * @author 孫濤 * 2016年5月10日 */ class Producer implements Runnable{ @Override public void run() { produce(); } private void produce() { while(true){ synchronized(queue){ while(queue.size() == queueSize){ try { System.out.println("隊列已滿,等待空余的空間"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); queue.notify(); } } queue.offer(1); // 每次插入一個元素 queue.notify(); System.out.println("向隊列取中插入一個元素,隊列剩余空間:"+(queueSize-queue.size())); } } } } }