阻塞式队列——生产者消费者模型


前言

生产者,消费者模型无论是平常开发中,还是面试中都是很经常用到的,它是通过一个容器来解决生产者和消费者的强耦合问题,生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不同等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里获取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力,这个阻塞队列就是用来给生产者和消费者解耦的


一、阻塞队列

  1. 阻塞队列就如同队列,先进先出
  2. 阻塞:表示这个队列是线程安全的
  3. 当队列满的时候往里面插入元素,此时会阻塞,一直阻塞到队列不满的时候才会完成插入
  4. 当对列为空的时候,从队列中取元素,此时也会阻塞,一直到队列不为空时,才能完成去元素操作

下面来康康代码如何实现的吧

public static void main(String[] args) throws InterruptedException {
        BlockingDeque<String> deque = new LinkedBlockingDeque<>(3);
        deque.put("a");
        deque.put("b");
        deque.put("c");
        //它的初始容量只有3,当我们放进去第四个的时候会出现什么样的效果?
        deque.put("d");
    }


}

结果就是一直处于阻塞状态直到可以放了
在这里插入图片描述


 public static void main(String[] args) throws InterruptedException {
        BlockingDeque<String> deque = new LinkedBlockingDeque<>(3);
        deque.put("a");
        deque.put("b");
        deque.put("c");
        //它的初始容量只有3,当我们放进去第四个的时候会出现什么样的效果?
     //   deque.put("d");
        System.out.println(deque.take());
        System.out.println(deque.take());
        System.out.println(deque.take());
        System.out.println(deque.take());
       // System.out.println(deque.take());

    }


}

同样的当我们只有三个,想要取更多的时候就会发生阻塞
在这里插入图片描述

传统的生产者、消费者问题

/**
 * A B操作同一变量,num
 * A+1,B-1  保证AB之间通信
 */
public class A {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }

}

class Data {
    private int num = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        if (num != 0) {
            //等待

            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知其他线程
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        if (num == 0) {
            //等待
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知
        this.notifyAll();
    }
}
  • 如果多个线程 A B C D
public static void main(String[] args) {
    Data data = new Data();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "A").start();

    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "B").start();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "C").start();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "D").start();
}
}


class Data {
    private int num = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        if (num != 0) {
            //等待

            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知其他线程
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        if (num == 0) {
            //等待
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知
        this.notifyAll();
    }
}

出现了异常情况
在这里插入图片描述

  • 防止虚假唤醒 :线程可以被唤醒,而不会接到通知,中断或超时
  • 等待总是出现在循环中,上面用if判断可能会造成虚假唤醒 下面是防止虚假唤醒的
public static void main(String[] args) {
    Data data = new Data();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "A").start();

    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "B").start();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "C").start();
    new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "D").start();
}
}


class Data {
    private int num = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        while (num != 0) {
            //等待

            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知其他线程
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (num == 0) {
            //等待
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + "->" + num);
        //通知
        this.notifyAll();
    }
}

JUC版的生产者消费者问题

public class B {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}


class Data2 {
    private int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    //+1
    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            while (num != 0) {//0
                //等待
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "->" + num);
            //通知其他线程
            condition.signalAll();
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0) {//1
                //等待
                condition.await();
            }
                num--;
                System.out.println(Thread.currentThread().getName() + "->" + num);
                //通知
                condition.signalAll();
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

-上面代码使用lock 中的await()和signalAll() 来实现线程之间相互通信
-但是还有个问题 这个代码每次运行结果都不一样,我们怎么能让A执行完执行B,B执行完执行C呢,那么就要用到精准通知signal()

/**
 * A->B->C  A执行完调用B  B执行完调用C  C执行完调用A 精准通知唤醒
 */
public class C {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data3.PrintA();
            }
        },"A").start();
        new Thread(()->{ for (int i = 0; i <10 ; i++) {
            data3.PrintB();
        }},"B").start();
        new Thread(()->{ for (int i = 0; i <10 ; i++) {
            data3.PrintC();
        }},"C").start();
    }
}
class Data3{
    private Lock lock = new ReentrantLock();
   private Condition condition1 = lock.newCondition();
   private  Condition condition2 = lock.newCondition();
   private  Condition condition3 = lock.newCondition();
   private  int  num =1; //1时A执行  2时B执行  3时C执行
    public void PrintA(){
       lock.lock();
       try{
           while (num!=1){
               condition1.await();
           }
           System.out.println(Thread.currentThread().getName()+"----A");
           //唤醒B
           condition2.signal();
           num=2;
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();
       }

    }
    public void PrintB(){
    lock.lock();
    try {
        while (num!=2){
            condition2.await();
        }
        System.out.println(Thread.currentThread().getName()+"----B");
        num=3;
        condition3.signal();

    }catch (Exception e){
        e.printStackTrace();
    }finally {
        lock.unlock();
    }
    }
    public void PrintC(){
        lock.lock();
        try {
            while (num!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"----C");
            num=1;
            condition1.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}


总结

注意BlockingQueue有四组API,如下图,每一种方法都有不同的用处,注意多写代码体会其中的差别,以及使用场景
在这里插入图片描述
关于生产者和消费者问题,包括里面涉及到的虚假唤醒,以及精准通知其实都很简单,动手写写就明白了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值