public boolean offer(E e) { checkNotNull(e); //创建新节点 final Node<E> newNode = new Node<E>(e); //循环开始,tail赋值给t,t赋值给p,此处是死循环,保证该入队操作能够一直重试,直到入队成功 for (Node<E> t = tail, p = t;;) { //p的next赋值给q Node<E> q = p.next; //如果q是null,说明tail的next是null,tail指向的是队列尾部,所以tail的next应该始终是null,此处表示p是最后一个节点 if (q == null) { // p是尾节点,则p的next节点是要入队列的节点 //cas操作,若失败表示其他线程对尾节点进行了修改,重新循环 //将p(p指向tail)的next指向新节点,若成功,进入if语句 if (p.casNext(null, newNode)) { //cas操作成功后,判断p是否等于t,p不等于t,设置newNode为新的尾节点,p不等于t表示什么?(此处有不明白,希望高手帮帮忙。) if (p != t) // hop two nodes at a time casTail(t, newNode); // Failure is OK. return true; } // p和q相等(这部分不是太理解,希望高手帮忙下) } else if (p == q) // We have fallen off list. If tail is unchanged, it // will also be off-list, in which case we need to // jump to head, from which all live nodes are always // reachable. Else the new tail is a better bet. p = (t != (t = tail)) ? t : head; else // Check for tail updates after two hops. p = (p != t && t != (t = tail)) ? t : q; } }
public E poll() { //设置循环标记 restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; //表头数据不为null,cas操作设置表头数据为null成功进入if if (item != null && p.casItem(item, null)) { //p不等于h,队列头发生了变化,更新队列头为p,返回原来队列头的item if (p != h) // hop two nodes at a time updateHead(h, ((q = p.next) != null) ? q : p); return item; } //队列头下一个节点为null,更新头尾p返回null else if ((q = p.next) == null) { updateHead(h, p); return null; } else if (p == q) continue restartFromHead; else p = q; } } }
peek()方法
返回队列头部的元素,跟poll方法类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public E peek() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; if (item != null || (q = p.next) == null) { updateHead(h, p); return item; } else if (p == q) continue restartFromHead; else p = q; } } }
size()方法
需要遍历队列,不推荐使用,尽量使用isEmpty()
1 2 3 4 5 6 7 8 9
public int size() { int count = 0; for (Node<E> p = first(); p != null; p = succ(p)) if (p.item != null) // Collection.size() spec says to max out if (++count == Integer.MAX_VALUE) break; return count; }