LinkedBlockingDeque自动阻塞,put和take方法的阻塞实现

LinkedBlockingDeque自动阻塞的双端队列。
增删元素的方法都是用ReentrantLock上锁的。
add方法无返回值,满了报异常,offer方法满了return false,put方法满了await自动阻塞。

以putFirst(E e)为例:

final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
public void putFirst(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            while (!linkFirst(node))//returns false if full.
                notFull.await(); //实现list满了的情况下就会自动阻塞
        } finally {
            lock.unlock();
        }
    }

以pollFirst()为例,peek,get等方法均不阻塞

public E pollFirst() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return unlinkFirst();
        } finally {
            lock.unlock();
        }
    }

只有take方法是自动阻塞的,调用condition的await方法进行阻塞

public E takeFirst() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            E x;
            while ( (x = unlinkFirst()) == null)
                notEmpty.await();
            return x;
        } finally {
            lock.unlock();
        }
    }
原创文章 64 获赞 27 访问量 9429

猜你喜欢

转载自blog.csdn.net/weixin_44893585/article/details/104580109