📜  实现 LinkedBlockingQueue API 的Java程序

📅  最后修改于: 2022-05-13 01:54:33.488000             🧑  作者: Mango

实现 LinkedBlockingQueue API 的Java程序

LinkedBlockingQueue API 是一个基于链接节点的可选有界队列。它以 FIFO(先进先出)顺序对元素进行排序。这个队列的头部是在队列中停留时间最长的元素,队列尾部是在队列中停留时间最短的元素。新元素插入队列尾部,队列检索操作获取队列头部元素。它属于Java .util.concurrent 包。它扩展了 Object、AbstractCollection 和 AbstractQueue 类。

容量参数是一种防止队列过度扩展的方法。容量(如果未指定)等于 Integer.MAX_VALUE。链接节点在每次插入时动态创建,除非这会使队列超出容量。

LinkedBlockingQueue API 是Java Collection Framework 的成员。

所有实现的接口:

1. Serializable
2. Iterable
3. Collection
4. BlockingQueue
5. Queue

参数: E — 集合中元素的类型

句法:

public class LinkedBlockingQueue extends AbstractQueue
implements BlockingQueue, Serializable

构造函数:

  1. public LinkedBlockingQueue() – 创建一个容量为 Integer.MAX_VALUE 的 LinkedBlockingQueue。
  2. public LinkedBlockingQueue(Collection c) – 创建一个容量为 Integer.MAX_VALUE 的 LinkedBlockingQueue,最初包含指定集合的元素。
  3. public LinkedBlockingQueue(int capacity) – 创建一个具有给定容量的 LinkedBlockingQueue。

执行:

例子

Java
// Java Program to Implement LinkedBlockingQueue API
 
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
 
public class BlockingQueue {
    private LinkedBlockingQueue q;
 
    // Creates a LinkedBlockingQueue with a size of
    // Integer.MAX_VALUE.
    public BlockingQueue()
    {
        q = new LinkedBlockingQueue();
    }
 
    // Creates a LinkedBlockingQueue initially containing
    // the elements of the given collection
    public BlockingQueue(Collection c)
    {
        q = new LinkedBlockingQueue(c);
    }
 
    // Creates a LinkedBlockingQueue with the given size
    public BlockingQueue(int size)
    {
        q = new LinkedBlockingQueue(size);
    }
 
    // Returns true if the queue contains the given element
    public boolean contains(Object o)
    {
        return q.contains(o);
    }
 
    // Removes all elements from the queue and adds them to
    // the given collection.
    public int drainTo(Collection c)
    {
        return q.drainTo(c);
    }
 
    //  Removes the elements from the queue and adds them to
    //  the given collection.
    public int drainTo(Collection c, int maxEle)
    {
        return q.drainTo(c, maxEle);
    }
 
    // Returns an iterator over the elements in the queue
    public Iterator iterator() { return q.iterator(); }
 
    // removes all the elements from the queue.
    void clear() { q.clear(); }
 
    // Inserts the given element at the end of the queue,
    // returning true upon inserting and false if the queue
    // is full.
    public boolean offer(E e) { return q.offer(e); }
 
    // inserts then given element at the end and wait for
    // the given time for the space to become available
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException
    {
        return q.offer(e, timeout, unit);
    }
 
    // Retrieves, but does not remove, the head of the
    // queue, or returns null if this queue is empty.
    public E peek() { return q.peek(); }
 
    //  Retrieves and removes the head of the queue
    public E poll() { return q.poll(); }
 
    // Retrieves and removes the head of the queue and wait
    // for the specified time for the element to become
    // available.
    public E poll(long tout, TimeUnit un)
        throws InterruptedException
    {
        return q.poll(tout, un);
    }
 
    // Returns the number of additional elements that the
    // queue can contain without blocking.
    public int remainingCapacity()
    {
        return q.remainingCapacity();
    }
 
    // Removes the specified element from the queue
    public boolean remove(Object o) { return q.remove(o); }
 
    // Returns the number of elements in the queue
    public int size() { return q.size(); }
 
    // Inserts the given element at the end of the queue,
    // wait for space to become available
    public void put(E e) throws InterruptedException
    {
        q.put(e);
    }
 
    // Retrieves and removes the head of the queue wait till
    // an element becomes available
    public E take() throws InterruptedException
    {
        return q.take();
    }
 
    // Returns an array containing all the elements in the
    // queue.
    public Object[] toArray() { return q.toArray(); }
 
    // Returns an array containing all of the elements in
    // the queue
    public  T[] toArray(T[] a) { return q.toArray(a); }
 
    // Returns a string representation of th collection.
    public String toString() { return q.toString(); }
 
    public static void main(String[] args)
    {
        BlockingQueue q
            = new BlockingQueue();
        try {
            q.put(1);
            q.put(2);
            q.put(3);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        System.out.println(
            "The elements of the LinkedBlockingQueue is ");
 
        Iterator i = q.iterator();
 
        while (i.hasNext()) {
            System.out.print(i.next() + "\t");
        }
        System.out.println();
 
        System.out.println("The remaining capacity is "
                           + q.remainingCapacity());
 
        System.out.println("3 removed " + q.remove(3));
 
        q.offer(6);
        q.offer(7);
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.peek());
 
        System.out.println(
            "The peak element of the LinkedBlockingQueue is "
            + q.poll());
 
        System.out.println(
            "The LinkedBlockingQueue contains 4 :"
            + q.contains(4));
 
        System.out.println(
            "The LinkedBlockingQueue contains 1 :"
            + q.contains(1));
 
        System.out.println(
            "The size of the LinkedBlockingQueue is "
            + q.size());
 
        System.out.println(q);
    }
}


输出
The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capacity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]


输出
The elements of the LinkedBlockingQueue is 
1    2    3    
The remaining capcity is 2147483644
3 removed true
The peak element of the LinkedBlockingQueue is 1
The peak element of the LinkedBlockingQueue is 1
The LinkedBlockingQueue contains 4 :false
The LinkedBlockingQueue contains 1 :false
The size of the LinkedBlockingQueue is 3
[2, 6, 7]

方法:

MethodTypeDescription
clear()void Removes all the elements of the LinkedBlockingQueue
contains(Object O)booleanReturns true if the queue contains the specified element.
iterator()Iterator()Returns an iterator over the elements in the queue.
offer(E e)booleanInserts the specified element at the tail of this queue if it is possible and returns true upon success otherwise false.
offer(E e, long timeout, TimeUnit unit)booleanInserts the specified element at the tail of the queue and wait for the specified time for the space to become available.
peek()ERetrieves, but does not remove, the head of the queue.
poll()ERetrieves and removes the head of the queue.
put(E e)voidInserts the specified element at the tail of this queue, waiting if necessary for space to become available.
remainingCapacity()intReturns the number of additional elements that this queue can ideally accept without blocking.
size()intReturns the size of the queue
toArray()Object[]Converts the queue to an array
drainTo(Collection c)intRemoves all available elements from the queue and adds them to the specified collection.
take()ERetrieves and removes the head of this queue, waiting if necessary until an element becomes available.
remove(Object O)booleanRemoves the specified element from the queue, if it is present.