|
| 1 | +package io.github.dunwu.javase.concurrent.thread; |
| 2 | + |
| 3 | +import java.util.PriorityQueue; |
| 4 | +import java.util.concurrent.locks.Condition; |
| 5 | +import java.util.concurrent.locks.Lock; |
| 6 | +import java.util.concurrent.locks.ReentrantLock; |
| 7 | + |
| 8 | +/** |
| 9 | + * 利用 Condition 实现生产者-消费者模型 |
| 10 | + * @author Zhang Peng |
| 11 | + * @date 2018/5/11 |
| 12 | + * @see ThreadWaitNotifyDemo02 |
| 13 | + */ |
| 14 | +public class ConditionDemo { |
| 15 | + |
| 16 | + private int queueSize = 10; |
| 17 | + private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize); |
| 18 | + private Lock lock = new ReentrantLock(); |
| 19 | + private Condition notFull = lock.newCondition(); |
| 20 | + private Condition notEmpty = lock.newCondition(); |
| 21 | + |
| 22 | + public static void main(String[] args) { |
| 23 | + ConditionDemo demo = new ConditionDemo(); |
| 24 | + Producer producer = demo.new Producer(); |
| 25 | + Consumer consumer = demo.new Consumer(); |
| 26 | + |
| 27 | + producer.start(); |
| 28 | + consumer.start(); |
| 29 | + } |
| 30 | + |
| 31 | + class Consumer extends Thread { |
| 32 | + |
| 33 | + @Override |
| 34 | + public void run() { |
| 35 | + consume(); |
| 36 | + } |
| 37 | + |
| 38 | + private void consume() { |
| 39 | + while (true) { |
| 40 | + lock.lock(); |
| 41 | + try { |
| 42 | + while (queue.size() == 0) { |
| 43 | + try { |
| 44 | + System.out.println("队列空,等待数据"); |
| 45 | + notEmpty.await(); |
| 46 | + } catch (InterruptedException e) { |
| 47 | + e.printStackTrace(); |
| 48 | + } |
| 49 | + } |
| 50 | + queue.poll(); //每次移走队首元素 |
| 51 | + notFull.signal(); |
| 52 | + System.out.println("从队列取走一个元素,队列剩余" + queue.size() + "个元素"); |
| 53 | + } finally { |
| 54 | + lock.unlock(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + class Producer extends Thread { |
| 61 | + |
| 62 | + @Override |
| 63 | + public void run() { |
| 64 | + produce(); |
| 65 | + } |
| 66 | + |
| 67 | + private void produce() { |
| 68 | + while (true) { |
| 69 | + lock.lock(); |
| 70 | + try { |
| 71 | + while (queue.size() == queueSize) { |
| 72 | + try { |
| 73 | + System.out.println("队列满,等待有空余空间"); |
| 74 | + notFull.await(); |
| 75 | + } catch (InterruptedException e) { |
| 76 | + e.printStackTrace(); |
| 77 | + } |
| 78 | + } |
| 79 | + queue.offer(1); //每次插入一个元素 |
| 80 | + notEmpty.signal(); |
| 81 | + System.out.println("向队列取中插入一个元素,队列剩余空间:" + (queueSize - queue.size())); |
| 82 | + } finally { |
| 83 | + lock.unlock(); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments