手撕算法之生产者与消费者模式

生产者与消费者模式

生产者消费者问题是一个多线程同步的经典问题,这个问题描述了生产者线程和消费者线程共享固定大小的缓冲区的问题。生产者不断的向缓冲区添加数据,消费者不断的消费缓冲区的数据,这个问题的关键是:
保证生产者在缓冲区满的时候不再向缓冲区添加数据,消费者在缓冲区空的时候也不会的时候消费缓冲区数据
解决思路:

  1. 生产者不断的生产,直到缓冲区满的时候,阻塞生产者线程,缓冲区不满的时候,继续生产
  2. 消费者不断的消费,直到缓冲区空的时候,阻塞消费者线程,缓冲区不空的时候,继续消费

使用wait,notify方式实现

public class ProducerAndConsumer {
   
   

    //消费者
    static class Consumer implements Runnable {
   
   
        private List<Integer> queue;

        public Consumer(List<Integer> queue) {
   
   
            this.queue = queue;
        }

        @Override
        public void run() {
   
   
            try {
   
   
                while (true) {
   
   
                    synchronized (queue) {
   
   
                        while (queue.isEmpty()) {
   
   
                            System.out.println("Queue is Empty");
                            queue.wait();
                        }
                        int i = queue.remove(0);
                        queue.notifyAll();
                        System.out.println(Thread.currentThread().getName() + "消费了:" + i + "还剩:" + queue.size());
                        Thread.sleep(100);
                    }
                }
            } catch (InterruptedException e) {
   
   

            }

        }
    }

    //生产者
    static class Producer implements Runnable {
   
   

        private List<Integer> queue;

        private int length; //容量

        public Producer(List<Integer> queue, int length) {
   
   
            this.queue = queue;
            this.length = length;
        }

        @Override
        public void run() {
   
   
            try {
   
   
                while (true) {
   
   
                    synchronized (queue) {
   
   
                        while (queue.size() > length) {
   
   
                            queue.wait();
                        }
                        queue.add(1);<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值