温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎么使用ArrayBlockingQueue解析阻塞队列

发布时间:2021-06-09 17:54:52 来源:亿速云 阅读:126 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关Java中怎么使用ArrayBlockingQueue解析阻塞队列,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

阻塞队列是java开发时常用的一个数据结构。首先看一下阻塞队列的作用是什么。阻塞队列的作用,从源码中类的注释中来了解,是最清晰准确的。

ArrayBlockingQueue是一个用数组实现的有界阻塞队列。提供FIFO的功能。队列头上的元素是在队列中呆了最长时间的元素,队列尾上的元素是在队列中呆了时间最短的元素。新元素会插入在队列尾部,从队列获取元素时会从队列头上获取。

这是一个传统的有界队列,在这个有界队列里,一个固定大小的数组用来保存生产者产生的元素和消费者获取的元素。一旦创建,大小不可改变。往已满的队列中尝试添加元素,会阻塞操作。从空的队列中获取元素,也会阻塞操作。

这个类为等待中的生产着和消费者线程排序提供可选的公平策略。默认情况下,顺序是没有保证的。但是,一个用fairness=true创建的队列可以保证FIFO特性。公平性通常会降低吞吐量,但是可以减少易变性并避免饥饿。

/**
 * A bounded {@linkplain BlockingQueue blocking queue} backed by an
 * array. This queue orders elements FIFO (first-in-first-out). The
 * <em>head</em> of the queue is that element that has been on the
 * queue the longest time. The <em>tail</em> of the queue is that
 * element that has been on the queue the shortest time. New elements
 * are inserted at the tail of the queue, and the queue retrieval
 * operations obtain elements at the head of the queue.
 * <p>This is a classic &quot;bounded buffer&quot;, in which a
 * fixed-sized array holds elements inserted by producers and
 * extracted by consumers. Once created, the capacity cannot be
 * changed. Attempts to {@code put} an element into a full queue
 * will result in the operation blocking; attempts to {@code take} an
 * element from an empty queue will similarly block.
 * <p>This class supports an optional fairness policy for ordering
 * waiting producer and consumer threads. By default, this ordering
 * is not guaranteed. However, a queue constructed with fairness set
 * to {@code true} grants threads access in FIFO order. Fairness
 * generally decreases throughput but reduces variability and avoids
 * starvation.
 * <p>This class and its iterator implement all of the
 * <em>optional</em> methods of the {@link Collection} and {@link
 * Iterator} interfaces.
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html" rel="external nofollow" >
 * Java Collections Framework</a>.
 * @since 1.5
 * @author Doug Lea
 * @param <E> the type of elements held in this collection
 **/

上述就是小编为大家分享的Java中怎么使用ArrayBlockingQueue解析阻塞队列了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI