利用J.U.C中的lock和condition實現生產者消費者模式

  1 package lockTest;
  2 
  3 import java.util.LinkedHashMap;
  4 import java.util.LinkedList;
  5 import java.util.concurrent.locks.Condition;
  6 import java.util.concurrent.locks.Lock;
  7 import java.util.concurrent.locks.ReentrantLock;
  8 
  9 public class ConditionTest {
 10 
 11     private Lock lock;
 12 
 13     private LinkedList<String> buffer;
 14 
 15     private int maxSize;
 16 
 17     private Condition notfullCondition;
 18 
 19     private Condition fullCondition;
 20 
 21     public ConditionTest(int maxSize) {
 22         this.maxSize = maxSize;
 23         lock = new ReentrantLock();
 24         buffer = new LinkedList<>();
 25         this.maxSize = maxSize;
 26         notfullCondition = lock.newCondition();
 27         fullCondition = lock.newCondition();
 28     }
 29 
 30     public void produce(String goods) throws InterruptedException {
 31 
 32         lock.lock();
 33 
 34         try {
 35 
 36             while (maxSize == buffer.size()) {
 37                 notfullCondition.await();
 38                 System.out.println("工廠產能達到極限,不能繼續進行生產了,停工一段時間");
 39             }
 40 
 41             //隊列沒有滿,能夠生產
 42             buffer.add(goods);
 43 
 44             System.out.println("哈哈,我生產了" + goods + ",通知消費者進行消費...");
 45             //通知消費者線程進行消費
 46             fullCondition.signalAll();
 47 
 48         } finally {
 49             lock.unlock();
 50         }
 51     }
 52 
 53     public String consume() throws InterruptedException {
 54 
 55         String goods = null;
 56         lock.lock();
 57 
 58         try {
 59 
 60             while (buffer.size() == 0) {
 61                 System.out.println("工廠的產品已經消費完了,暫時不能剁手了");
 62                 fullCondition.await();
 63             }
 64 
 65             //開始消費
 66             goods = buffer.poll();
 67             System.out.println("哈哈,我消費" + goods + ",通知工廠進行生產...");
 68             //通知生成者
 69             notfullCondition.signalAll();
 70 
 71         } finally {
 72             lock.unlock();
 73         }
 74 
 75         return goods;
 76     }
 77 
 78 
 79     public static void main(String[] args) {
 80 
 81         ConditionTest conditionTest = new ConditionTest(100);
 82 
 83         new Thread(() -> {
 84 
 85             for (int i = 0; i < 1000000; i++) {
 86                 try {
 87                     conditionTest.produce("筆記本電腦" + i);
 88                 } catch (InterruptedException e) {
 89                     e.printStackTrace();
 90                 }
 91             }
 92 
 93         }, "produce").start();
 94 
 95 
 96         new Thread(() -> {
 97 
 98             while (true) {
 99                 try {
100                     conditionTest.consume();
101                 } catch (InterruptedException e) {
102                     e.printStackTrace();
103                 }
104             }
105 
106         }, "consume").start();
107 
108     }
109 
110 }
相關文章
相關標籤/搜索