日期:2014-05-16 浏览次数:20460 次
?
?
package java.util.concurrent;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.*;
?
?* @since 1.5
?* @author Doug Lea
?* @param <E> the type of elements held in this collection
?*
?*/
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
? ? ? ? implements BlockingQueue<E>, java.io.Serializable {
? ? private static final long serialVersionUID = -6903933977591709194L;
?
?
?
? ? /**
? ? ?* Linked list node class
? ? ?*/
? ? static class Node<E> {
? ? ? ? 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)
? ? ? ? ?*/
?
? ? ? ? Node<E> next;
? ? ? ? Node(E x) { item = x; }
? ? }
?
? ? /** The capacity bound, or Integer.MAX_VALUE if none */
? ? private final int capacity;
?
? ? /** Current number of elements */
? ? private final AtomicInteger count = new AtomicInteger(0);
?
? ? /** Head of linked list */
? ? private transient Node<E> head;
?
? ? /** Tail of linked list */
? ? private transient Node<E> last;
?
? ? /** Lock held by take, poll, etc */
? ? private final ReentrantLock takeLock = new ReentrantLock();
?
? ? /** Wait queue for waiting takes */
? ? private final Condition notEmpty = takeLock.newCondition();
?
? ? /** Lock held by put, offer, etc */
? ? private final ReentrantLock putLock = new ReentrantLock();
?
? ? /** Wait queue for waiting puts */
? ? private final Condition notFull = putLock.newCondition();
?
? ? /**
? ? ?* Signals a waiting take. Called only from put/offer (which do not
? ? ?* otherwise ordinarily lock takeLock.)
? ? ?*/
? ? private void signalNotEmpty() {
? ? ? ? final ReentrantLock takeLock = this.takeLock;
? ? ? ? takeLock.lock();
? ? ? ? try {
? ? ? ? ? ? notEmpty.signal();
? ? ? ? } finally {
? ? ? ? ? ? takeLock.unlock();
? ? ? ? }
? ? }
?
? ? /**
? ? ?* Signals a waiting put. Called only from take/poll.
? ? ?*/
? ? private void signalNotFull() {
? ? ? ? final ReentrantLock putLock = this.putLock;
? ? ? ? putLock.lock();
? ? ? ? try {
? ? ? ? ? ? notFull.signal();
? ? ? ? } finally {
? ? ? ? ? ? putLock.unlock();
? ? ? ? }
? ? }
?
? ? /**
? ? ?*?创建一个节点,并将其链接在队列的末端.
? ? ?* @param x the item
? ? ?*/
? ? private void enqueue(E x) {
? ? ? ? // assert putLock.isHeldByCurrentThread();
? ? ? ? last = last.next = new Node<E>(x);
? ? }
?
? ? /**
? ? ?*?从队列的顶端删除一个节点。
? ? ?