阻塞队列BlockingQueue实战及其原理分析

1.BlockingQueue介绍

1. Queue(队列)顶层接口

add(E) 添加元素,成功返回true,否则返回异常

offer(E) 添加元素,成功返回true,否则返回false

remove() 返回并移除队首元素,队列为空返回异常

poll() 返回并移除队首元素,队列为空返回null

peek() 获取队首元素,队列为空则返回null

BlockingQueue继承于Queue,提供了阻塞的特性,入队和出队都有常用的方法

入队:put(E) offer(E) offer(E,long,TimeUnit)

出队:poll(),poll(long,TimeUnit),take()

1.1 BlockingQueue常用方法实战

演示常用四种方法:add remove offer poll使用,符合队列先进先出的特性。

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest {

    public static void main(String[] args) {

        //测试add remove offer poll
        Queue addblockingQueue = new ArrayBlockingQueue(2);
        addblockingQueue.add(1);
        addblockingQueue.add(2);
//        addblockingQueue.add(3);//放入第三个Exception in thread "main" java.lang.IllegalStateException: Queue full

//        addblockingQueue.remove();
//        addblockingQueue.remove();
//        addblockingQueue.remove();//移出第三个Exception in thread "main" java.util.NoSuchElementException

        Queue offerblockingQueue = new ArrayBlockingQueue(2);
        System.out.println(offerblockingQueue.offer(1));//返回true
        System.out.println(offerblockingQueue.offer(2));//返回true
        System.out.println(offerblockingQueue.offer(3));//返回false

        System.out.println(offerblockingQueue.poll());//返回1
        System.out.println(offerblockingQueue.poll());//返回1 符合队列特性先进先出
        System.out.println(offerblockingQueue.poll());//返回null
    }
}

1.2 常用的队列

队列的应用场景:队列是线程的安全的,我们经常在线程池,中间件比如生产者消费者模式和nacos注册中心中使用。 

1.2.1 ArrayBlockingQueue介绍(TODO)

 ArrayBlockingQueue是一个有界阻塞队列,底层基于数组实现,使用reenTrantLock来保证线程安全,一般情况下使用是一个不错的选择,但是在高并发场景下,因为用reenTrantLock加锁和解锁,插入和取出的速度会称为性能瓶颈,在高并发场景下一般使用linkedBlockingQueue,实战代码见1.1

源码分析关注点:

1.构造方法

2.使用的元素:数组,reenTrantLock,两个条件队列(没满和为空)

3.put和take方法

 1.2.2 linkedBlockingQueue介绍(TODO)

linkedBlockingQueue是一个链表实现的有界阻塞队列,但是它的默认最大值是Integer.MAX_VALUE,是一个很大的数字,所以我们经常说它是一个无界的阻塞队列。当内存不足时,会跑出OOM问题,所以为了解决这个问题,一般在初始化时就要指定队列的大小。linkedBlockingQueue也是使用的ReentrantLock来保证线程安全,与arrayBlockingQueue的区别也于它有两把锁,一把用于入队,一把用于出队,也有两个条件队列,保证入队和出队的唤醒。

源码分析关注点:

1.构造方法

2.使用的元素

3.put,take,remove方法

1.2.3 LinkedBlockingDeque介绍

Deque是一个阻塞双端队列,特性跟linkedBolckingQueue差不多,跟linkedBolckingQueue不同的是只有一把reentrantLock锁,多了几个API,能够操作队首和队尾元素。

addFirst(E e)
addLast(E e)
offerFirst(E e)
offerLast(E e)

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

bingtanghulu_6

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

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

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

打赏作者

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

抵扣说明:

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

余额充值