publicintdrainTo(Collection<? super E> c){ return drainTo(c, Integer.MAX_VALUE); }
publicintdrainTo(Collection<? super E> c, int maxElements){ checkNotNull(c); if (c == this) thrownew IllegalArgumentException(); if (maxElements <= 0) return0; final Object[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { int n = Math.min(maxElements, count); int take = takeIndex; int i = 0; try { while (i < n) { @SuppressWarnings("unchecked") E x = (E) items[take]; c.add(x); items[take] = null; if (++take == items.length) take = 0; i++; } return n; } finally { // Restore invariants even if c.add() threw if (i > 0) { count -= i; takeIndex = take; if (itrs != null) { if (count == 0) itrs.queueIsEmpty(); elseif (i > take) itrs.takeIndexWrapped(); } for (; i > 0 && lock.hasWaiters(notFull); i--) notFull.signal(); } } } finally { lock.unlock(); } }
public E peek(){ final ReentrantLock lock = this.lock; lock.lock(); try { return itemAt(takeIndex); // null when queue is empty } finally { lock.unlock(); } }
publicbooleanremove(Object o){ if (o == null) returnfalse; final Object[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { if (count > 0) { finalint putIndex = this.putIndex; int i = takeIndex; // 从takeIndex一直遍历到putIndex,直到找到和元素o相同的元素,调用removeAt进行删除 do { if (o.equals(items[i])) { removeAt(i); returntrue; } if (++i == items.length) i = 0; } while (i != putIndex); } returnfalse; } finally { lock.unlock(); } }
voidremoveAt(finalint removeIndex){ final Object[] items = this.items; if (removeIndex == takeIndex) { // removing front item; just advance items[takeIndex] = null; if (++takeIndex == items.length) takeIndex = 0; count--; if (itrs != null) itrs.elementDequeued(); } else { // an "interior" remove // slide over all others up through putIndex. finalint putIndex = this.putIndex; for (int i = removeIndex;;) { int next = i + 1; if (next == items.length) next = 0; if (next != putIndex) { items[i] = items[next]; i = next; } else { items[i] = null; this.putIndex = i; break; } } count--; if (itrs != null) itrs.removedAt(removeIndex); } notFull.signal(); }