生产者与消费者.md 发表于 2020-08-10 更新于 2021-11-21 分类于 并发 本文字数: 1.7k 阅读时长 ≈ 2 分钟 栗子1:使用wait/notify方法来实现1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980public class ProducerAndConsumerExample { public static void main(String[] args) { Container container = new Container(); new Thread(new Consumer(container)).start(); new Thread(new Producer(container)).start(); }}class Consumer implements Runnable { private Container container; public Consumer(Container container) { this.container = container; } @Override public void run() { try { for (int i = 0; i < 100; i++) { container.take(); } } catch (InterruptedException e) { e.printStackTrace(); } }}class Producer implements Runnable { private Container container; public Producer(Container container) { this.container = container; } @Override public void run() { try { for (int i = 0; i < 100; i++) { container.put(); } } catch (InterruptedException e) { e.printStackTrace(); } }}// 实现类似于阻塞队列的容器class Container { private Integer maxSize = 30; private LinkedList<Integer> queue; public Container() { queue = new LinkedList<>(); } public synchronized void put() throws InterruptedException { // 队列已满,阻塞等待,使用while而不是使用if while (this.queue.size() == maxSize) { this.wait(); } this.queue.add(1); System.out.println("添加到容器,容器内还有" + this.queue.size() + "个数据"); // 通知消费者取数据 this.notifyAll(); } public synchronized void take() throws InterruptedException { // 队列为空,阻塞等待,使用while而不是使用if while (this.queue.size() == 0) { this.wait(); } this.queue.poll(); System.out.println("取出数据,容器内还有" + this.queue.size() + "个数据"); // 通知生产者生产数据 this.notifyAll(); }} 一毛也是爱~ 打赏 微信支付