DelayQueue源码分析

DelayQueue<E>继承于AbstractQueue<E>实现BlockingQueue<E>

内部变量包括ReentrantLock 类型的lock以及条件Condition类型的available 同时内部维护一个优先级队列q。

内部的方法offer(E e):

public boolean offer(E e) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        E first = q.peek();
        q.offer(e);
        if (first == null || e.compareTo(first) < 0)
            available.signalAll();
        return true;
    } finally {
        lock.unlock();
    }
}

内部方法take()

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        for (;;) {
            E first = q.peek();
            if (first == null) {
                available.await();
            } else {
                long delay =  first.getDelay(TimeUnit.NANOSECONDS);
                if (delay > 0) {
                    long tl = available.awaitNanos(delay);
                } else {
                    E x = q.poll();
                    assert x != null;
                    if (q.size() != 0)
                        available.signalAll(); // wake up other takers
                    return x;

                }
            }
        }
    } finally {
        lock.unlock();
    }
}

注意take()方法与poll方法的最大不同是take方法会在循环里不断获取队列中的数据直到得到了数据为止。而poll方法只会获取一次如果获取不到则会直接返回

posted @ 2017-08-23 11:41  菜鸟麦迪粉  阅读(231)  评论(0编辑  收藏  举报