peek类操作其实比较简单。因为有一个head节点去维护当前的队首元素。只有判断先first(head的后继)是否为空就好。
public E peek() {
if (count.get() == 0)
return null;
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
Node<E> first = head.next;
if (first == null)
return null;
else
return first.item;
} finally {
takeLock.unlock();
}
}
public boolean remove(Object o) {
if (o == null) return false;
fullyLock();//获取存元素锁和取元素锁(不允许存或取元素),因为有可能同时涉及到头尾结点的访问问题
try {
for (Node<E> trail = head, p = trail.next; p != null; trail = p, p = p.next) {// 遍历整个链表
if (o.equals(p.item)) {// 结点的值与指定值相等
unlink(p, trail); // 断开结点
return true;
}
}
return false;
} finally {
fullyUnlock();
}
}
void unlink(Node<E> p, Node<E> trail) {
p.item = null;
trail.next = p.next;// 断开p结点
if (last == p) // 尾节点为p结点
last = trail; // 重新赋值尾节点
if (count.getAndDecrement() == capacity)
notFull.signal();
}
void fullyLock() {
putLock.lock();
takeLock.lock();
}
void fullyUnlock() {
takeLock.unlock();
putLock.unlock();
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。