基于链表的队列LinkedBlockingQueue学习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于链表的队列LinkedBlockingQueue学习相关的知识,希望对你有一定的参考价值。
LinkedBlockingQueue为先进先出队列
1.链表中的节点,next为后继节点
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
2.三种构造方法a.容量为最大值 b.容量为指定大小 c.容量为最大值,使用Collection c初始化队列
public LinkedBlockingQueue() {this(Integer.MAX_VALUE);}
public LinkedBlockingQueue(int capacity) {......}
public LinkedBlockingQueue(Collection<? extends E> c) {......}
3.常用方法add(),offer(),put(),poll(),peek(),clear()
add():调用父类AbstractQueue中的方法,父类调用LinkedBlockingQueue.offer(e)方法
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
offer():等待指定时间插入一个元素,如果时间到元素还没有添加进去就返回false。
Inserts the specified element at the tail of this queue, waiting if necessary up to the specified wait time for
space to become available.
public boolean offer(E e) {......}
public boolean offer(E e, long timeout, TimeUnit unit){......}
put():Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.
public void put(E e){......}
poll():Removes a node from head of queue.
public E poll() {......}
public E poll(long timeout, TimeUnit unit) {......}
如果队列数量等于0,等待指定时间后返回null
peek():查看队列的头,并不移除该元素
public E peek() {return first.item;}
clear():Atomically removes all of the elements from this queue.
public void clear() {......}
以上是关于基于链表的队列LinkedBlockingQueue学习的主要内容,如果未能解决你的问题,请参考以下文章