ArrayBlockingQueue

java 队列阻塞方法ArrayBlockingQueue学习

一笑奈何 提交于 2019-12-02 05:26:34
本例介绍一个特殊的队列:BlockingQueue,如果BlockQueue是空的,从BlockingQueue取东西的操作将会被阻断进入等待状态,直到BlockingQueue进了东西才会被唤醒.同样,如果BlockingQueue是满的,任何试图往里存东西的操作也会被阻断进入等待状态,直到BlockingQueue里有空间才会被唤醒继续操作. 使用BlockingQueue的关键技术点如下: 1.BlockingQueue定义的常用方法如下: 1)add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则招聘异常 2)offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false. 3)put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续. 4)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null 5)take():取走BlockingQueue里排在首位的对象

JDK容器学习之Queue: ArrayBlockingQueue

北慕城南 提交于 2019-12-01 04:52:31
基于数组阻塞队列 ArrayBlockingQueue 前面学习了基于数组的非阻塞双端队列 ArrayDeque ,其内部维护一个数组和指向队列头和队列尾索引的两个成员变量;本篇则探究下基于数组的阻塞队列是什么样的数据结构,又有什么特性,相较于 ArrayDeque 又有什么异同;然后就是使用场景了 I. 底层数据结构 先看内部成员变量定义, 和 ArrayDequeue 相比,差别不大,一个数组,两个索引;此外多了一个锁和两个判定条件 /** The queued items */ final Object[] items; /** items index for next take, poll, peek or remove */ int takeIndex; /** items index for next put, offer, or add */ int putIndex; /** Number of elements in the queue */ int count; /** Main lock guarding all access */ final ReentrantLock lock; /** Condition for waiting takes */ private final Condition notEmpty; /** Condition for