package java.util.concurrent
public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable
可以设置队列的长度,默认为Integer.MAX_VALUE
数据元素操作
public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable
线程安全的链式阻塞队列
内部有个static class Node<E> 实现链式结构
构造函数
/**
* Creates a {@code LinkedBlockingQueue} with a capacity of
* {@link Integer#MAX_VALUE}.
*/
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
/**
* Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
*
* @param capacity the capacity of this queue
* @throws IllegalArgumentException if {@code capacity} is not greater
* than zero
*/
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node<E>(null);
}
/**
* Creates a {@code LinkedBlockingQueue} with a capacity of
* {@link Integer#MAX_VALUE}, initially containing the elements of the
* given collection,
* added in traversal order of the collection's iterator.
*
* @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
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 new NullPointerException();
if (n == capacity)
throw new IllegalStateException("Queue full");
enqueue(new Node<E>(e));
++n;
}
count.set(n);
} finally {
putLock.unlock();
}
}
可以设置队列的长度,默认为Integer.MAX_VALUE
或从一个Collection,创建LinkedBlockingQueue
内部的锁和相关条件
/** 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();
数据元素操作
add、remove
add会调用offer();
add:添加元素, 返回是否操作成功的boolean标识。 链表未满才可添加
remove:删除元素,返回是否操作成功的boolean标识。 链表未空才可删除
offer、poll
offer:添加元素, 返回是否操作成功的boolean标识。 链表未满才可添加
poll:删除元素,返回被删除的元素。若无元素被删除,返回null
put、take
put:阻塞式添加元素,当链表满了,阻塞线程。
take:阻塞式删除元素,当链表空了,阻塞线程。 返回移除的元素。
LinkedBlockingQueue 是一个先进先出(FIFO)的阻塞式队列
添加时,会加到链尾
移除时,会移除链头
本文介绍Java并发包中LinkedBlockingQueue的实现原理与使用方法。它是一个线程安全的链式阻塞队列,支持FIFO操作,可用于多线程间的任务传递。文章详细解释了其构造函数、内部数据结构及主要方法。
924

被折叠的 条评论
为什么被折叠?



