3、删除元素
public E peek() {
if (count.get() == 0)
return null;
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
Node
first = head.next;
if (first == null)
return null;
else
return first.item;
} finally {
takeLock.unlock();
}
}
4、迭代元素
public Iteratoriterator() { return new Itr(); }
private class Itr implements Iterator{ // 当前节点 private Node current; // 上一次返回的节点 private Node lastRet; // 当前节点对应的值 private E currentElement; Itr() { // 同时获取“插入锁putLock” 和 “取出锁takeLock” fullyLock(); try { // 设置“当前元素”为“队列表头的下一节点”,即为队列的第一个有效节点 current = head.next; if (current != null) currentElement = current.item; } finally { // 释放“插入锁putLock” 和 “取出锁takeLock” fullyUnlock(); } } // 返回“下一个节点是否为null” public boolean hasNext() { return current != null; } private Node nextNode(Node p) { for (;;) { Node s = p.next; if (s == p) return head.next; if (s == null || s.item != null) return s; p = s; } } // 返回下一个节点 public E next() { fullyLock(); try { if (current == null) throw new NoSuchElementException(); E x = currentElement; lastRet = current; current = nextNode(current); currentElement = (current == null) null : current.item; return x; } finally { fullyUnlock(); } } // 删除下一个节点 public void remove() { if (lastRet == null) throw new IllegalStateException(); fullyLock(); try { Node node = lastRet; lastRet = null; for (Node trail = head, p = trail.next; p != null; trail = p, p = p.next) { if (p == node) { unlink(p, trail); break; } } } finally { fullyUnlock(); } } }