Java 7之多线程并发容器 - LinkedBlockingQueue(二)

2014-11-24 02:36:08 · 作者: · 浏览: 1
.toNanos(timeout); final AtomicInteger count = this.count; final ReentrantLock takeLock = this.takeLock; takeLock.lockInterruptibly(); try { while (count.get() == 0) { if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } x = dequeue(); c = count.getAndDecrement(); if (c > 1) notEmpty.signal(); } finally { takeLock.unlock(); } if (c == capacity) signalNotFull(); return x; } public E poll() { final AtomicInteger count = this.count; if (count.get() == 0) return null; E x = null; int c = -1; final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { if (count.get() > 0) { x = dequeue(); c = count.getAndDecrement(); if (c > 1) notEmpty.signal(); } } finally { takeLock.unlock(); } if (c == capacity) signalNotFull(); return x; }

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 Iterator
  
    iterator() {
  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(); } } }