Queue接口定义

本文详细介绍了 Java 中 Queue 接口的设计理念及其主要方法,包括插入、移除和检查队列元素的操作方式。探讨了不同类型的队列,如 FIFO 和 LIFO 的特点,并解释了如何处理队列中的 null 元素。
/*
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/

package java.util;

/**
* A collection designed for holding elements prior to processing.
* Besides basic {@link java.util.Collection Collection} operations,
* queues provide additional insertion, extraction, and inspection
* operations. Each of these methods exists in two forms: one throws
* an exception if the operation fails, the other returns a special
* value (either <tt>null</tt> or <tt>false</tt>, depending on the
* operation). The latter form of the insert operation is designed
* specifically for use with capacity-restricted <tt>Queue</tt>
* implementations; in most implementations, insert operations cannot
* fail.
*
Queue优先处理元素,除了Collection的基本操作之外,Queue添加了另外插入,拉取,
检查3个操作。每一种方法都有两种格式,一种操作失败,则抛出异常,另一种返回一个
特殊的值,null或false,依赖于操作。后一种形式的插入操作是用capacity-restricted
Queue来实现的,在大多数的实现中,插入操作不会失败。
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td></td>
* <td ALIGN=CENTER>[i]Throws exception[/i]</td>
* <td ALIGN=CENTER>[i]Returns special value[/i]</td>
* </tr>
* <tr> 插入,提供
* <td><b>Insert</b></td>
* <td>{@link #add add(e)}</td>
* <td>{@link #offer offer(e)}</td>
* </tr>
* <tr>移除,拉取
* <td><b>Remove</b></td>
* <td>{@link #remove remove()}</td>
* <td>{@link #poll poll()}</td>
* </tr>
* <tr>检查
* <td><b>Examine</b></td>
* <td>{@link #element element()}</td>
* <td>{@link #peek peek()}</td>
* </tr>
* </table>
*
* <p>Queues typically, but do not necessarily, order elements in a
* FIFO (first-in-first-out) manner. Among the exceptions are
* priority queues, which order elements according to a supplied
* comparator, or the elements' natural ordering, and LIFO queues (or
* stacks) which order the elements LIFO (last-in-first-out).
* Whatever the ordering used, the [i]head[/i] of the queue is that
* element which would be removed by a call to {@link #remove() } or
* {@link #poll()}. In a FIFO queue, all new elements are inserted at
* the [i] tail[/i] of the queue. Other kinds of queues may use
* different placement rules. Every <tt>Queue</tt> implementation
* must specify its ordering properties.
*
Queues除了非必要之外,元素的模式为FIFO。其中的一个例外是优先级队列,元素根据
比较器或者本身的顺序添加队列( LIFO queues)中。无论什么顺序,对头的元素将会
被#remove或#poll消费/移除。在先进先出队列中,所有的新元素插入到队尾,其他队列
可能会用其他的策略添加新元素。每一种队列的实现要明确排序策略。

* <p>The {@link #offer offer} method inserts an element if possible,
* otherwise returning <tt>false</tt>. This differs from the {@link
* java.util.Collection#add Collection.add} method, which can fail to
* add an element only by throwing an unchecked exception. The
* <tt>offer</tt> method is designed for use when failure is a normal,
* rather than exceptional occurrence, for example, in fixed-capacity
* (or "bounded") queues.
*
如果可能,offer操作,插入元素时,会返回false。这个与集合类的add方法不同的时,
集合类add方法,当失败时,则抛出一个unchecked异常。offer操作设计为在一个正常模式下的失败,
而不异常发生,比如队列容量有限。
* <p>The {@link #remove()} and {@link #poll()} methods remove and
* return the head of the queue.
* Exactly which element is removed from the queue is a
* function of the queue's ordering policy, which differs from
* implementation to implementation. The <tt>remove()</tt> and
* <tt>poll()</tt> methods differ only in their behavior when the
* queue is empty: the <tt>remove()</tt> method throws an exception,
* while the <tt>poll()</tt> method returns <tt>null</tt>.
*
* <p>The {@link #element()} and {@link #peek()} methods return, but do
* not remove, the head of the queue.
*
remove和poll元素将从队列头部消费一个元素。不同的队列实现消费队列元素顺序时,可能有不同的
策略。remove和poll操作不同的时,当队列为空时,remove抛出异常 ,poll则返回null。

* <p>The <tt>Queue</tt> interface does not define the <i>blocking queue
* methods</i>, which are common in concurrent programming. These methods,
* which wait for elements to appear or for space to become available, are
* defined in the {@link java.util.concurrent.BlockingQueue} interface, which
* extends this interface.
*
Queue没有定义阻塞队列的方法,这些方法会在并发编程中用到。这些方法,比如,在队列为空时,
消费者阻塞等待队列有元素可利用,这些方法在BlockingQueue接口中定义。
* <p><tt>Queue</tt> implementations generally do not allow insertion
* of <tt>null</tt> elements, although some implementations, such as
* {@link LinkedList}, do not prohibit insertion of <tt>null</tt>.
* Even in the implementations that permit it, <tt>null</tt> should
* not be inserted into a <tt>Queue</tt>, as <tt>null</tt> is also
* used as a special return value by the <tt>poll</tt> method to
* indicate that the queue contains no elements.
队列的实现通常不允许插入null,尽管LinkedList不禁止插入null值。即使允许插入null,
我们也利用利用poll操作,来暗示队列中没有元素。
*
* <p><tt>Queue</tt> implementations generally do not define
* element-based versions of methods <tt>equals</tt> and
* <tt>hashCode</tt> but instead inherit the identity based versions
* from class <tt>Object</tt>, because element-based equality is not
* always well-defined for queues with the same elements but different
* ordering properties.
*
Queue的实现通常不会定义equals和hashCode方法,而是继承自Object,因为hash值和值相等
,但是顺序属性可能不同。
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @see java.util.Collection
* @see LinkedList
* @see PriorityQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.BlockingQueue
* @see java.util.concurrent.ArrayBlockingQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.PriorityBlockingQueue
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
public interface Queue<E> extends Collection<E> {
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
* if no space is currently available.
*
在有界队列未满的情况下,添加元素,返回true,没空间可利用,则抛出异常IllegalStateException
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
boolean add(E e);

/**
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions.
* When using a capacity-restricted queue, this method is generally
* preferable to {@link #add}, which can fail to insert an element only
* by throwing an exception.
*
在有界队列未满的情况下,添加元素,立即成功;当队列为有界是,add更好,因为越界抛出异常
* @param e the element to add
* @return <tt>true</tt> if the element was added to this queue, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
boolean offer(E e);

/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
从对头消费一个元素,当队列为空,抛出异常
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();

/**
* Retrieves and removes the head of this queue,
* or returns <tt>null</tt> if this queue is empty.
*
从对头消费一个元素,当队列为空,返回null
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
E poll();

/**
* Retrieves, but does not remove, the head of this queue. This method
* differs from {@link #peek peek} only in that it throws an exception
* if this queue is empty.
*
检查队列中是否有元素,当队列为空,抛出异常
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E element();

/**
* Retrieves, but does not remove, the head of this queue,
* or returns <tt>null</tt> if this queue is empty.
*
检查队列中是否有元素,当队列为空,返回null
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
E peek();
}

附:Collection

[img]http://dl2.iteye.com/upload/attachment/0123/7389/b6cd3a9f-61aa-397e-9285-3cea7fbc51b3.png[/img]
<think>我们已有之前的详细回答,现在用户再次提问要求提供BlockingQueue的详细介绍及使用指南。我们需要整合引用内容,确保回答准确且符合用户需求。 关键点:使用方法、特性、实现类等。 根据之前的回答和引用内容,我们需要注意: 1. 核心特性:阻塞机制、线程安全、队列类型(实现类) 2. 核心方法:put、take、offer、poll等 3. 应用场景 4. 实现原理(简要) 同时,引用内容中提供了额外的细节: 引用[1]:介绍了ArrayBlockingQueue和LinkedBlockingQueue的区别,以及DelayQueue等。 引用[2]:提供了BlockingQueue接口的方法列表。 引用[3]:提到有界队列的创建方式(容量作为参数)。 引用[4]:提供了带超时时间的offer方法。 因此,我们将调整结构,确保涵盖以下内容: 一、BlockingQueue概述 二、核心特性 三、常用实现类及其特点 四、核心方法详解(包括超时方法) 五、应用场景 六、实现原理(简要) 七、注意事项 最后,生成相关问题。 注意:引用标记要自然地添加在相关内容的末尾。 </think>### BlockingQueue 详细介绍及使用指南 #### 一、核心特性 1. **阻塞机制** - 生产者调用 `put(E e)` 时队列满则阻塞,直到有空位[^1] - 消费者调用 `take()` 时队列空则阻塞,直到有新元素[^1] ```java // 生产者线程 blockingQueue.put(item); // 队列满时阻塞 // 消费者线程 Item item = blockingQueue.take(); // 队列空时阻塞 ``` 2. **线程安全** 所有操作内置锁机制,支持多线程并发(如 `ArrayBlockingQueue`, `LinkedBlockingQueue`)[^2] 3. **队列边界控制** - 有界队列:创建时需指定容量(如 `new LinkedBlockingQueue<>(10)`)[^3] - 无界队列:默认 `Integer.MAX_VALUE`(如 `PriorityBlockingQueue`) --- #### 二、常用实现类对比 | 实现类 | 数据结构 | 边界 | 特点 | |-----------------------|-------------|--------|-------------------------------| | `ArrayBlockingQueue` | 数组 | 有界 | 固定容量,FIFO,一把锁控制[^1] | | `LinkedBlockingQueue` | 链表 | 可选 | 默认无界,吞吐量高,两把锁[^1] | | `PriorityBlockingQueue`| 优先级堆 | 无界 | 按Comparator排序 | | `DelayQueue` | 优先级堆 | 无界 | 元素需实现 `Delayed` 接口 | | `SynchronousQueue` | 无存储 | 特殊 | 生产者必须等待消费者取走[^2] | > **关键区别**: > - `ArrayBlockingQueue` 性能稳定,`LinkedBlockingQueue` 吞吐量更高[^1] > - `SynchronousQueue` 适用于线程间直接传递(如 `newCachedThreadPool` 的默认队列) --- #### 三、核心方法详解 | 方法 | 行为说明 | |-------------------------------|--------------------------------------------------------------------------| | **阻塞操作** | | | `void put(E e)` | 插入元素,队列满时无限期阻塞 | | `E take()` | 移除元素,队列空时无限期阻塞 | | **非阻塞操作** | | | `boolean offer(E e)` | 插入元素(立即返回),成功返回 `true`,失败 `false` | | `E poll()` | 移除元素(立即返回),有元素则返回,无则 `null` | | **带超时操作** | | | `boolean offer(E e, long timeout, TimeUnit unit)` | 队列满时等待指定时间,超时返回 `false`[^4] | | `E poll(long timeout, TimeUnit unit)` | 队列空时等待指定时间,超时返回 `null` | | **检查操作** | | | `E peek()` | 查看队首元素(不移除) | | `int remainingCapacity()` | 返回队列剩余容量 | | `int drainTo(Collection<? super E> c)` | 一次性移出所有元素到指定集合 | --- #### 四、使用示例 **1. 生产者-消费者模型** ```java BlockingQueue<String> queue = new ArrayBlockingQueue<>(5); // 生产者 new Thread(() -> { queue.put("Task1"); queue.offer("Task2", 1, TimeUnit.SECONDS); // 带超时插入 }).start(); // 消费者 new Thread(() -> { String task = queue.take(); System.out.println("Processed: " + task); }).start(); ``` **2. 优先级任务处理** ```java BlockingQueue<Task> queue = new PriorityBlockingQueue<>(10, Comparator.comparingInt(Task::getPriority)); queue.put(new Task("High", 1)); // 高优先级 queue.put(new Task("Low", 3)); // 低优先级 // 按优先级顺序取出 Task task = queue.take(); // 先取出优先级1的任务 ``` --- #### 五、注意事项 1. **资源控制** - 无界队列(如 `PriorityBlockingQueue`)可能导致 `OutOfMemoryError` - 建议生产环境使用有界队列并监控 `remainingCapacity()`[^3] 2. **公平性** - `ArrayBlockingQueue` 可设置公平锁(构造函数传入 `true`),避免线程饥饿 3. **性能权衡** - `LinkedBlockingQueue` 吞吐量更高,但内存占用大于数组实现 - `SynchronousQueue` 适用高频小数据传递,吞吐量最佳[^2] ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值