【Java】用Java库中自带的阻塞队列以及用阻塞队列实现生产者-消费者模型

1、阻塞队列(BlockingDeque)

 首先我们来认识一下什么是堵塞队列

阻塞队列即实现了线程安全和阻塞的队列。在队列为空时,获取元素的线程会等待队列存放元素变为非空;在队列满时,存放元素的线程会等待队列取出元素变为不满。

阻塞队列常应用于生产者-消费者模型

我们常用的阻塞队列主要有两类

LinkedBlockingDeque

ArrayBlockingQueue

使用LinkedBlockingDeque

BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>();

使用ArrayBlockingQueue

ArrayBlockingQueue<String> blockingDeque = new ArrayBlockingQueue<>(100);
//100表示队列容量

2、阻塞队列中常用的方法

常用的方法有三个:put(),take(),peek()

put()

put()方法用于在阻塞队列中存放元素

blockingDeque.put(1);

 take()

take()方法用于获取并取出队首元素

System.out.println(blockingDeque.take());

peek()

peek()用于获取队首元素

System.out.println(blockingDeque.peek());

3、用阻塞队列实现生产者-消费者模型

这里我们用LinkedBlockingDeque类

我们用两个线程分别来给阻塞队列添加/取出元素,以此来实现生产者/消费者模型 

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class demo1 {
    public static void main(String[] args) throws InterruptedException {
        BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>();

        Thread thread1 = new Thread(()->{
            int n = 0;
            while (true){
                try {
                    blockingDeque.put(n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产元素"+n);
                n++;

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread thread2 = new Thread(()->{
            while (true){
                try {
                    System.out.println("消费元素"+blockingDeque.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        thread1.start();
        thread2.start();

    }
}

运行结果

 注意:上面代码中,我们在生产者线程里使用了sleep()休眠,以此来控制生产消费的速度

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙河板混

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值