LinkedBlockingQueue是BlockingQueue中的其中一个,其实现方式为单向链表,下面看其具体实现。(均为JDK8)
一、构造函数
在LinkedBlockingQueue中有三个构造函数,如下图,
1、LinkedBlockingQueue()
这是一个无参的构造函数,其定义如下,
publicLinkedBlockingQueue() {this(Integer.MAX_VALUE);
}
在这个构造函数中调用了有参的构造函数,传入的整型值为Integer所能表示的最大值(0x7fffffff)。下面看这个带参数的构造方法。
2、LinkedBlockingQueue(int capacity)
这是一个整型参数的构造方法其,定义如下,
public LinkedBlockingQueue(intcapacity) {if (capacity <= 0) throw newIllegalArgumentException();this.capacity =capacity;
last= head = new Node(null);
}
从其实现上来看,其整型参数代表此队列的容量,即元素的最大个数;然后初始化了last和head两个变量,我们猜last应该是此队列的尾元素、head为此队列的头元素。这里有一个Node类,下面看Node类的实现,
static class Node{
E item;/*** One of:
* - the real successor Node
* - this Node, meaning the successor is head.next
* - null, meaning there is no successor (this is the last node)*/Nodenext;
Node(E x) { item=x; }
}
Node是LinkedBlockingQueue的静态内部类,也是组成此队列的节点元素,其内部有两个属性,一个Item代表节点元素,next指向下一个Node节点,这样就可以得出LinkedBlockingQueue的结构是使用Node连接起来,头节点为head,尾节点为last。
3、LinkedBlockingQueue(Collection extends E> c)
此构造方法是使用一个集合类进行构造,其定义如下
public LinkedBlockingQueue(Collection extends E>c) {this(Integer.MAX_VALUE);final ReentrantLock putLock = this.putLock;
putLock.lock();//Never contended, but necessary for visibility
try{int n = 0;for(E e : c) {if (e == null)throw newNullPointerException();if (n ==capacity)throw new IllegalStateException("Queue full");
enqueue(new Node(e));++n;
}
count.set(n);
}finally{
putLock.unlock();
}
}
4、LinkedBlockingQueue的属性
从上面的构造函数中可以大体了解其属性有容量(capacity),队列中的元素数量(count)、头节点(head)、尾节点(last)等,如下
/**The capacity bound, or Integer.MAX_VALUE if none*/
private final intcapacity;/**Current number of elements*/
private final Atom