ConcurrentLinkedQueue是线程安全的队列,它适用于“高并发”的场景。它是一个基于连接节点的无界线程html
安全队列,按照 FIFO(先进先出)原则对元素进行排序。队列元素中不能够放置null元素(内部实现的特殊java
节点除外)。数组
ConcurrentLinkedQueue的数据结构,以下图所示:安全
说明:数据结构
ConcurrentLinkedQueue按照 FIFO(先进先出)原则对元素进行排序。元素都是从尾部插入到链表,从头多线程
部开始返回。并发
volatile。关于volatile,咱们知道它的语义包含:“即对一个volatile变量的读,老是能看到(任意线程)对这ide
个volatile变量最后的写入”。ConcurrentLinkedQueue就是经过volatile来实现多线程对竞争资源的互斥访高并发
问的。线程
// 建立一个最初为空的 ConcurrentLinkedQueue。 ConcurrentLinkedQueue() // 建立一个最初包含给定 collection 元素的 ConcurrentLinkedQueue,按照此 collection 迭代器的遍历顺序来添加元素。 ConcurrentLinkedQueue(Collection<? extends E> c) // 将指定元素插入此队列的尾部。 boolean add(E e) // 若是此队列包含指定元素,则返回 true。 boolean contains(Object o) // 若是此队列不包含任何元素,则返回 true。 boolean isEmpty() // 返回在此队列元素上以恰当顺序进行迭代的迭代器。 Iterator<E> iterator() // 将指定元素插入此队列的尾部。 boolean offer(E e) // 获取但不移除此队列的头;若是此队列为空,则返回 null。 E peek() // 获取并移除此队列的头,若是此队列为空,则返回 null。 E poll() // 从队列中移除指定元素的单个实例(若是存在)。 boolean remove(Object o) // 返回此队列中的元素数量。 int size() // 返回以恰当顺序包含此队列全部元素的数组。 Object[] toArray() // 返回以恰当顺序包含此队列全部元素的数组;返回数组的运行时类型是指定数组的运行时类型。 <T> T[] toArray(T[] a)
import java.util.*; import java.util.concurrent.*; /* * ConcurrentLinkedQueue是“线程安全”的队列,而LinkedList是非线程安全的。 * * 下面是“多个线程同时操做而且遍历queue”的示例 * (01) 当queue是ConcurrentLinkedQueue对象时,程序能正常运行。 * (02) 当queue是LinkedList对象时,程序会产生ConcurrentModificationException异常。 * * @author skywang */ public class ConcurrentLinkedQueueDemo1 { // TODO: queue是LinkedList对象时,程序会出错。 //private static Queue<String> queue = new LinkedList<String>(); private static Queue<String> queue = new ConcurrentLinkedQueue<String>(); public static void main(String[] args) { // 同时启动两个线程对queue进行操做! new MyThread("ta").start(); new MyThread("tb").start(); } private static void printAll() { String value; Iterator iter = queue.iterator(); while (iter.hasNext()) { value = (String) iter.next(); System.out.print(value + ", "); } System.out.println(); } private static class MyThread extends Thread { MyThread(String name) { super(name); } @Override public void run() { int i = 0; while (i++ < 6) { // “线程名” + "-" + "序号" String val = Thread.currentThread().getName() + i; queue.add(val); // 经过“Iterator”遍历queue。 printAll(); } } } }
结果说明:若是将源码中的queue改为LinkedList对象时,程序会产生ConcurrentModificationException异常。