生产者消费者模型的特点:
保证生产者不会在缓冲区满的时候继续向缓冲区放入数据,而消费者也不会在缓冲区空的时候,消耗数据。
当缓冲区满的时候,生产者会进入休眠状态,当下次消费者开始消耗缓冲区的数据时,生产者才会被唤醒,开始往缓冲区中添加数据;当缓冲区空的时候,消费者也会进入休眠状态,直到生产者往缓冲区中添加数据时才会被唤醒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 import lombok.extern.slf4j.Slf4j;import java.util.concurrent.TimeUnit;public class ProducerAndConsumerDemo { public static void main (String[] args) { Store store = new Store(10 ); new Thread(new Producer(store), "producer" ).start(); new Thread(new Consumer(store), "consumer1" ).start(); new Thread(new Consumer(store), "consumer2" ).start(); } } @Slf 4jclass Store { private Integer capacity; private Integer count = 0 ; public Store (Integer capacity) { this .capacity = capacity; } public Boolean isFull () { return this .count >= this .capacity; } public Boolean isEmpty () { return this .count <= 0 ; } synchronized void produce () throws InterruptedException { if (this .isFull()) { log.info("仓库满了,停止生产" ); wait(); } else if (this .isEmpty()) { log.info("仓库空了, 放入第" + count + "号位置,并通知消费者" ); this .count++; TimeUnit.SECONDS.sleep(1 ); notifyAll(); } else { log.info("放入第" + count + "号位置" ); this .count++; TimeUnit.SECONDS.sleep(1 ); } } synchronized void consume () throws InterruptedException { if (this .isEmpty()) { log.info("仓库空了,停止消费" ); wait(); } else if (this .isFull()) { this .count--; log.info("仓库满了,取出第" + count + "号位置, 并通知生产者" ); TimeUnit.SECONDS.sleep(2 ); notifyAll(); } else { this .count--; log.info("取出第" + count + "号位置" ); TimeUnit.SECONDS.sleep(2 ); } } } class Producer implements Runnable { private Store store; public Producer (Store store) { this .store = store; } @Override public void run () { while (true ) { try { store.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { private Store store; public Consumer (Store store) { this .store = store; } @Override public void run () { while (true ) { try { store.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } } }