Queue常用类解析之BlockingQueue(一):PriorityBlockingQueue、DelayQueue和DelayedWorkQueue

Queue常用类解析之PriorityQueue
Queue常用类解析之ConcurrentLinkedQueue

一、简介

BlockingQueue是concurrent包下的一个并发Queue的接口,称为阻塞队列。
与ConcurrentLinkedQueue通过CAS方式来实现并发不同,BlockingQueue的并发方案是阻塞等待。
Jdk为BlockingQueue提供了不少的实现类,主要用于生产者-消费者模式的场景,如线程池就通过BlockingQueue管理任务。
下面将针对BlockingQueue的一些实现类展开介绍。

1. 常用Queue类图

常用Queue类图

2. BlockingQueue核心方法描述

BlockingQueue方法描述

二、PriorityBlockingQueue

从命名上就能看出,PriorityBlockingQueue是PriorityQueue的并发阻塞版本。
在PriorityBlockingQueue的数据结构是数组表示的最小堆,入队时不会造成阻塞,当队列中元素已满时会抛出OutOfMemoryError异常。出队时如果队列中没有元素线程会陷入阻塞状态,由入队方法进行唤醒。

1. 属性

/**
* Priority queue represented as a balanced binary heap: the two
 * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
 * priority queue is ordered by comparator, or by the elements'
 * natural ordering, if comparator is null: For each node n in the
 * heap and each descendant d of n, n <= d.  The element with the
 * lowest value is in queue[0], assuming the queue is nonempty.
 */
private transient Object[] queue;

/**
 * The number of elements in the priority queue.
 */
private transient int size;

/**
 * The comparator, or null if priority queue uses elements'
 * natural ordering.
 */
private transient Comparator<? super E> comparator;

/**
 * Lock used for all public operations
 */
private final ReentrantLock lock;

/**
 * Condition for blocking when empty
 */
private final Condition notEmpty;

/**
 * Spinlock for allocation, acquired via CAS.
 */
private transient volatile int allocationSpinLock;

queue、size和comparator和PriorityQueue中的含义并没有什么不同。
我们主要关注的就是后面的3和并发属性:lock, notEm

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值