zoukankan      html  css  js  c++  java
  • jdk Queue

    jdk原生类中有队列Queue,在很多地方用到 例如Executors.newCachedThreadPool中SynchronousQueue,newFixThreadPool中LinkedBlockingQueue

    ,newScheduledThreadPool中DelayedWorkQueue等,

    先看一下类图

    Queue注释如下

    A collection designed for holding elements prior to processing. Besides basic 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 null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.

    Summary of Queue methods
      Throws exception Returns special value
    Insert add(e) offer(e)
    Remove remove() poll()
    Examine element() peek()

    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 head of the queue is that element which would be removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

    The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

    The remove() and 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 remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null.

    The element() and peek() methods return, but do not remove, the head of the queue.

    The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the java.util.concurrent.BlockingQueue interface, which extends this interface.

    Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

    Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

    This interface is a member of the Java Collections Framework.

    翻译

    设计用于在处理之前保持元素的集合。 除了基本的Collection操作外,队列还提供额外的插入,提取和检查操作。 这些方法中的每一种都以两种形式存在:一种在操作失败时抛出异常,另一种返回特殊值(null或false,具体取决于操作)。 后一种形式的插入操作专门用于容量限制的队列实现; 在大多数实现中,插入操作不会失败。

    Summary of Queue methods
      Throws exception Returns special value
    Insert add(e) offer(e)
    Remove remove() poll()
    Examine element() peek()

    队列通常(但不一定)以FIFO(先进先出)方式对元素进行排序。其中的例外是优先级队列,它根据提供的比较器对元素进行排序,或者元素的自然顺序,以及LIFO队列(或堆栈),它们对元素LIFO(后进先出)进行排序。无论使用什么顺序,队列的头部是通过调用remove()或poll()来移除的元素。在FIFO队列中,所有新元素都插入队列的尾部。其他类型的队列可能使用不同的放置规则。每个Queue实现都必须指定其排序属性。

    如果可能,offer方法插入一个元素,否则返回false。这与Collection.add方法不同,后者只能通过抛出未经检查的异常来添加元素。 offer方法设计用于当故障是正常而非异常发生时,例如,在固定容量(或“有界”)队列中。

    remove()和poll()方法删除并返回队列的头部。确切地说,从队列中删除哪个元素是队列排序策略的一个功能,该策略因实现而异。 remove()和poll()方法的不同之处仅在于队列为空时的行为:remove()方法抛出异常,而poll()方法返回null。

    element()和peek()方法返回但不删除队列的头部。

    Queue接口未定义阻塞队列方法,这在并发编程中很常见。这些等待元素出现或空间可用的方法在java.util.concurrent.BlockingQueue接口中定义,该接口扩展了此接口。

    队列实现通常不允许插入null元素,尽管某些实现(如LinkedList)不禁止插入null。即使在允许它的实现中,也不应将null插入到Queue中,因为null也被poll方法用作特殊返回值,以指示队列不包含任何元素。

    队列实现通常不定义基于元素的方法equals和hashCode版本,而是从Object类继承基于身份的版本,因为基于元素的相等性并不总是为具有相同元素但具有不同排序属性的队列定义良好。

    此接口是Java Collections Framework的成员。

    Queue的直接子类 包括BlockingQueue、AbstractQueue、Deque

    BlockingQueue

    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

    BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:

    Summary of BlockingQueue methods
      Throws exception Special value Blocks Times out
    Insert add(e) offer(e) put(e) offer(e, time, unit)
    Remove remove() poll() take() poll(time, unit)
    Examine element() peek() not applicable not applicable

    A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

    A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.

    BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the java.util.Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

    BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

    A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.

    Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

     class Producer implements Runnable {
       private final BlockingQueue queue;
       Producer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while (true) { queue.put(produce()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       Object produce() { ... }
     }
    
     class Consumer implements Runnable {
       private final BlockingQueue queue;
       Consumer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while (true) { consume(queue.take()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       void consume(Object x) { ... }
     }
    
     class Setup {
       void main() {
         BlockingQueue q = new SomeQueueImplementation();
         Producer p = new Producer(q);
         Consumer c1 = new Consumer(q);
         Consumer c2 = new Consumer(q);
         new Thread(p).start();
         new Thread(c1).start();
         new Thread(c2).start();
       }
     }}

    Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

    This interface is a member of the Java Collections Framework.

     翻译

    一个java.util.Queue,额外支持在检索元素时等待队列变为非空的操作,并在存储元素时等待队列中的空间可用。
    BlockingQueue方法有四种形式,有不同的处理操作方式,不能立即满足,但可能在将来的某个时候得到满足:一个抛出异常,第二个返回一个特殊值(null或false,取决于 操作),第三个无限期地阻塞当前线程直到操作成功,并且第四个块在放弃之前仅用于给定的最大时间限制。 这些方法总结在下表中:

    Summary of BlockingQueue methods
    Throws exception Special value Blocks Times out
    Insert add(e) offer(e) put(e) offer(e, time, unit)
    Remove remove() poll() take() poll(time, unit)
    Examine element() peek() not applicable not applicable

    BlockingQueue不接受null元素。实现在尝试添加,放置或提供null时抛出NullPointerException。 null用作标记值以指示轮询操作失败。

    BlockingQueue可以是容量限制的。在任何给定时间,它可能具有剩余容量,超过该容量,不能在没有阻塞的情况下放置其他元素。没有任何内在容量限制的BlockingQueue始终报告Integer.MAX_VALUE的剩余容量。

    BlockingQueue实现主要用于生产者 - 使用者队列,但另外支持java.util.Collection接口。因此,例如,可以使用remove(x)从队列中删除任意元素。然而,这些操作通常不是非常有效地执行,并且仅用于偶尔使用,例如当排队的消息被取消时。

    BlockingQueue实现是线程安全的。所有排队方法都使用内部锁或其他形式的并发控制以原子方式实现其效果。但是,除非在实现中另有说明,否则批量收集操作addAll,containsAll,retainAll和removeAll不一定以原子方式执行。因此,例如,在仅添加c中的一些元素之后,addAll(c)可能会失败(抛出异常)。

    BlockingQueue本质上不支持任何类型的“关闭”或“关闭”操作,以指示不再添加任何项目。这些功能的需求和使用倾向于依赖于实现。例如,一种常见的策略是生产者插入特殊的流末端或毒物对象,这些对象在被消费者采用时会相应地进行解释。

    用法示例,基于典型的生产者 - 消费者场景。请注意,BlockingQueue可以安全地与多个生产者和多个消费者一起使用。

    代码部分。。。。。。

    内存一致性效果:与其他并发集合一样,在将对象放入BlockingQueue之前,线程中的操作发生在从另一个线程中的BlockingQueue访问或删除该元素之后的操作之前。

    此接口是Java Collections Framework的成员。

    AbstractQueue

    This class provides skeletal implementations of some Queue operations. The implementations in this class are appropriate when the base implementation does not allow null elements. Methods add, remove, and element are based on offer, poll, and peek, respectively, but throw exceptions instead of indicating failure via false or null returns.

    A Queue implementation that extends this class must minimally define a method Queue.offer which does not permit insertion of null elements, along with methods Queue.peek, Queue.poll, Collection.size, and Collection.iterator. Typically, additional methods will be overridden as well. If these requirements cannot be met, consider instead subclassing AbstractCollection.

    This class is a member of the Java Collections Framework.

    翻译

    此类提供某些Queue操作的骨干实现。 当基本实现不允许null元素时,此类中的实现是适当的。 方法add,remove和element分别基于offer,poll和peek,但抛出异常而不是通过false或null返回指示失败。

    扩展此类的Queue实现必须最低限度地定义一个方法Queue.offer,该方法不允许插入null元素,以及Queue.peek,Queue.poll,Collection.size和Collection.iterator方法。 通常,还会覆盖其他方法。 如果无法满足这些要求,请考虑继承AbstractCollection。

    此类是Java Collections Framework的成员。

    Deque

    A linear collection that supports element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

    This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Deque implementations; in most implementations, insert operations cannot fail.

    The twelve methods described above are summarized in the following table:

    Summary of Deque methods
    First Element (Head) Last Element (Tail)
    Throws exception Special value Throws exception Special value
    Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
    Remove removeFirst() pollFirst() removeLast() pollLast()
    Examine getFirst() peekFirst() getLast() peekLast()

    This interface extends the Queue interface. When a deque is used as a queue, FIFO (First-In-First-Out) behavior results. Elements are added at the end of the deque and removed from the beginning. The methods inherited from the Queue interface are precisely equivalent to Deque methods as indicated in the following table:

    Comparison of Queue and Deque methods
    Queue Method Equivalent Deque Method
    add(e) addLast(e)
    offer(e) offerLast(e)
    remove() removeFirst()
    poll() pollFirst()
    element() getFirst()
    peek() peekFirst()

    Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque. Stack methods are precisely equivalent to Deque methods as indicated in the table below:

    Comparison of Stack and Deque methods
    Stack Method Equivalent Deque Method
    push(e) addFirst(e)
    pop() removeFirst()
    peek() peekFirst()

    Note that the peek method works equally well when a deque is used as a queue or a stack; in either case, elements are drawn from the beginning of the deque.

    This interface provides two methods to remove interior elements, removeFirstOccurrence and removeLastOccurrence.

    Unlike the List interface, this interface does not provide support for indexed access to elements.

    While Deque implementations are not strictly required to prohibit the insertion of null elements, they are strongly encouraged to do so. Users of any Deque implementations that do allow null elements are strongly encouraged not to take advantage of the ability to insert nulls. This is so because null is used as a special return value by various methods to indicated that the deque is empty.

    Deque implementations generally do not define element-based versions of the equals and hashCode methods, but instead inherit the identity-based versions from class Object.

    This interface is a member of the Java Collections Framework.

    翻译

    线性集合,支持两端插入和移除元素。名称deque是“双端队列”的缩写,通常发音为“deck”。大多数Deque实现对它们可能包含的元素数量没有固定限制,但是此接口支持容量限制的deques以及没有固定大小限制的deques。

    此接口定义了访问双端队列两端元素的方法。提供了插入,移除和检查元素的方法。这些方法中的每一种都以两种形式存在:一种在操作失败时抛出异常,另一种返回特殊值(null或false,具体取决于操作)。后一种形式的插入操作专门设计用于容量限制的Deque实现;在大多数实现中,插入操作不会失败。

    上述十二种方法总结在下表中:

    Summary of Deque methods
    First Element (Head) Last Element (Tail)
    Throws exception Special value Throws exception Special value
    Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
    Remove removeFirst() pollFirst() removeLast() pollLast()
    Examine getFirst() peekFirst() getLast() peekLast()


    此接口扩展了Queue接口。当deque用作队列时,会产生FIFO(先进先出)行为。元素在双端队列的末尾添加并从头开始删除。从Queue接口继承的方法与Deque方法完全等效,如下表所示:

    Comparison of Queue and Deque methods
    Queue Method Equivalent Deque Method
    add(e) addLast(e)
    offer(e) offerLast(e)
    remove() removeFirst()
    poll() pollFirst()
    element() getFirst()
    peek() peekFirst()


    Deques也可以用作LIFO(后进先出)堆栈。应优先使用此接口,而不是传统的Stack类。当deque用作堆栈时,元素将从双端队列的开头推出并弹出。堆栈方法与Deque方法完全等效,如下表所示:

    Comparison of Stack and Deque methods
    Stack Method Equivalent Deque Method
    push(e) addFirst(e)
    pop() removeFirst()
    peek() peekFirst()


    请注意,当deque用作队列或堆栈时,peek方法同样有效;在任何一种情况下,元素都是从双端队列的开头绘制的。

    此接口提供了两种方法来删除内部元素,removeFirstOccurrence和removeLastOccurrence。

    与List接口不同,此接口不支持对元素的索引访问。

    虽然严格要求Deque实现禁止插入null元素,但强烈建议他们这样做。强烈建议任何允许null元素的Deque实现的用户不要利用插入空值的能力。这是因为null通过各种方法用作特殊返回值,以指示deque为空。

    Deque实现通常不定义equals和hashCode方法的基于元素的版本,而是从Object类继承基于身份的版本。

    此接口是Java Collections Framework的成员

  • 相关阅读:
    分不清npm cnpm npx nvm ?
    gulp 中对于css文件的压缩合并出现的unable to minify JavaScript问题
    JS实现选项卡和JQ实现选项卡
    前端性能的优化
    JS中事件绑定的方式以及事件监听和事件的委托
    简易轮播图和无缝轮播图的实现
    ES6中对象的扩展以及新增方法
    javascript的基本介绍和发展
    this浅谈
    浅谈DOM的概念和作用
  • 原文地址:https://www.cnblogs.com/toUpdating/p/10105964.html
Copyright © 2011-2022 走看看