聊聊LinkedBlockingQueue链表阻塞队列

简介
LinkedBlockingQueue 是一个基于链表的有限队列(理论上它是无限的)。只支持一段入队,另一端出队。无阻塞对应LindedList,它们除了一个线程安全一个线程不安全以外,最大的区别是LinkedList可以放null值。

BlockingQueue 接口

public interface BlockingQueue<E> extends Queue<E>

BlockingQueue 继承Queue

 

BlockingQueue 方法

// 添加,满时抛异常
boolean add(E e);
// 添加,满时返回false
boolean offer(E e);
// 添加,满时阻塞
void put(E e) throws InterruptedException;
// 添加,满时阻塞,超时返回false
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
// 出队,空时阻塞
E take() throws InterruptedException;
// 出队,空时阻塞,超时返回null
E poll(long timeout, TimeUnit unit) throws InterruptedException;
// 剩余容量(理想情况下)
int remainingCapacity();
// 删除元素,失败返回false(这里和remove()不一样)
boolean remove(Object o);
// 是否包含
public boolean contains(Object o);
// 从该队列中移除所有可用元素,并将它们添加到给定集合中
int drainTo(Collection<? super E> c);
// 从该队列中移除最多给定数量的可用元素,并将它们添加到给定集合中。
int drainTo(Collection<? super E> c, int maxElements);

 

BlockingDeque 接口

public interface BlockingDeque<E> extends BlockingQueue<E>, Deque<E>

BlockingDeque 继承BlockingQueue 和 Deque 两个接口

 

BlockingDeque 方法

// 头部添加
void addFirst(E e);
// 尾部添加
void addLast(E e);
// 头部添加
boolean offerFirst(E e);
// 尾部添加
boolean offerLast(E e);
// 头部添加,满时阻塞
void putFirst(E e) throws InterruptedException;
// 尾部添加,满时阻塞
void putLast(E e) throws InterruptedException;
// 头部添加,满时阻塞,超时返回false
boolean offerFirst(E e, long timeout, TimeUnit unit)
        throws InterruptedException;
// 尾部添加,满时阻塞,超时返回false
boolean offerLast(E e, long timeout, TimeUnit unit)
        throws InterruptedException;
// 头部出队,空时阻塞
E takeFirst() throws InterruptedException;
// 尾部出队,空时阻塞
E takeLast() throws InterruptedException;
// 头部出队,空时阻塞,超时返回null
E pollFirst(long timeout, TimeUnit unit)
        throws InterruptedException;
// 尾部出队,空时阻塞,超时返回null
E pollLast(long timeout, TimeUnit unit)
        throws InterruptedException;
// 从头部删除元素
boolean removeFirstOccurrence(Object o);
// 从尾部删除元素
boolean removeLastOccurrence(Object o);
// 添加,满时抛异常
boolean add(E e);
// 添加,满时返回false
boolean offer(E e);
// 添加,满时阻塞
void put(E e) throws InterruptedException;
// 添加,满时阻塞,超时返回false
boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;
// 出队,空时抛异常
E remove();
// 出队,空时返回null
E poll();
// 出队,空时阻塞
E take() throws InterruptedException;
// 出队,空时阻塞,超时返回null
E poll(long timeout, TimeUnit unit)
        throws InterruptedException;
// 查询,空时异常
E element();
// 查询,空时返回null
E peek();
// 删除元素,空时返回false
boolean remove(Object o);
// 是否包含
public boolean contains(Object o);
// 长度
public int size();
// 迭代器
Iterator<E> iterator();
// 添加,满时抛异常
void push(E e);

阻塞队列扩展非阻塞队列,提供阻塞,阻塞超时等方法。当队列中为空时,从队列中获取元素的操作将被阻塞,当队列满时,向队列中添加元素的操作将被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其它的线程往队列中插入新的元素。同样,试图往满的队列中添加新元素的线程也会被阻塞,直到有其他的线程使队列重新变的空闲起来。

抛出异常:当队列满时,再向队列中插入元素,则会抛出IllegalStateException异常。当队列空时,再向队列中获取元素,则会抛出NoSuchElementException异常。

返回特殊值:当队列满时,向队列中添加元素,则返回false,否则返回true。当队列为空时,向队列中获取元素,则返回null,否则返回元素。

一直阻塞:当阻塞队列满时,如果生产者向队列中插入元素,则队列会一直阻塞当前线程,直到队列可用或响应中断退出。当阻塞队列为空时,如果消费者线程向阻塞队列中获取数据,则队列会一直阻塞当前线程,直到队列空闲或响应中断退出。

超时退出:当队列满时,如果生产线程向队列中添加元素,则队列会阻塞生产线程一段时间,超过指定的时间则退出返回false。当队列为空时,消费线程从队列中移除元素,则队列会阻塞一段时间,如果超过指定时间退出返回null。

LinkedBlockingQueue 类

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable

继承AbstractQueue,并实现BlockingQueue接口

 

重要内部类Node

static class Node<E>


Node 属性

// 元素
E item;
// 下级节点
Node<E> next;
Node 构造函数


构造函数

Node(E x) { item = x; }

Node 是对元素封装

 

LinkedBlockingQueue 属性

// 链表最大长度
private final int capacity;
// 元素个数
private final AtomicInteger count = new AtomicInteger();
// 头结点
transient Node<E> head;
// 尾结点
private transient Node<E> last;
// 读锁
private final ReentrantLock takeLock = new ReentrantLock();
// 空监控
private final Condition notEmpty = takeLock.newCondition();
// 写锁
private final ReentrantLock putLock = new ReentrantLock();
// 满监控
private final Condition notFull = putLock.newCondition();

 

LinkedBlockingQueue 构造函数

// 默认构造函数
public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}
// 固定长度构造函数
public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    last = head = new Node<E>(null);
}
// 使用线性集合初始化
public LinkedBlockingQueue(Collection<? extends E> c) {
    // 初始化队列
    this(Integer.MAX_VALUE);
    // 获取写锁
    final ReentrantLock putLock = this.putLock;
    // 加锁
    putLock.lock(); 
    try {
        int n = 0;
        // 遍历参数
        for (E e : c) {
            // 元素为空抛异常(一样不能添加空元素)
            if (e == null)
                throw new NullPointerException();
            // 满了抛异常
            if (n == capacity)
                throw new IllegalStateException("Queue full");
            // 存入元素
            enqueue(new Node<E>(e));
            ++n;
        }
        // 元素个数
        count.set(n);
    } finally {
        // 解锁
        putLock.unlock();
    }
}

 

LinkedBlockingQueue 基础方法
长度

public int size() {
    return count.get();
}

剩余长度

public int remainingCapacity() {
    return capacity - count.get();
}

放开读限制

private void signalNotEmpty() {
    // 获取读锁
    final ReentrantLock takeLock = this.takeLock;
    // 加锁(已经获取锁的线程处于等待,其他线程是可以获取锁的)
    takeLock.lock();
    try {
        // 放开读限制
        notEmpty.signal();
    } finally {
        // 解锁
        takeLock.unlock();
    }
}

放开写限制

private void signalNotFull() {
    final ReentrantLock putLock = this.putLock;
    // 加锁(已经获取锁的线程处于等待,其他线程是可以获取锁的)
    putLock.lock();
    try {
        // 放开写限制
        notFull.signal();
    } finally {
        // 解锁
        putLock.unlock();
    }
}

获取读锁和写锁

void fullyLock() {
    putLock.lock();
    takeLock.lock();
}

释放读锁和写锁

void fullyUnlock() {
    takeLock.unlock();
    putLock.unlock();
}

 

LinkedBlockingQueue 添加
添加,满时阻塞

public void put(E e) throws InterruptedException {
    // 添加空元素抛异常
    if (e == null) throw new NullPointerException();
    int c = -1;
    Node<E> node = new Node<E>(e);
    // 获取写锁
    final ReentrantLock putLock = this.putLock;
    // 获取当前元素个数
    final AtomicInteger count = this.count;
    // 加锁
    putLock.lockInterruptibly();
    try {
        // 元素个数是否等于最大长度
        while (count.get() == capacity) {
            // 满监控等待
            notFull.await();
        }
        // 存入
        enqueue(node);
        // 元素个数加1(先返回后加)
        c = count.getAndIncrement();
        // 判断是否满了
        if (c + 1 < capacity)
            // 没满,放开写入限制
            notFull.signal();
    } finally {
        // 解锁
        putLock.unlock();
    }
    // count原值为0时,才会去放开读限制
    if (c == 0)
        signalNotEmpty();
}

添加,满时等待,超时退出

public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
    // 添加空元素抛异常
    if (e == null) throw new NullPointerException();
    // 等待时间
    long nanos = unit.toNanos(timeout);
    int c = -1;
    // 获取写锁
    final ReentrantLock putLock = this.putLock;
    // 获取当前元素个数
    final AtomicInteger count = this.count;
    // 加锁
    putLock.lockInterruptibly();
    try {
        // 元素个数是否等于最大长度
        while (count.get() == capacity) {
            // 等待时间是否小于0
            if (nanos <= 0)
                return false;
            // awaitNanos超时,则返回值小于等于0
            nanos = notFull.awaitNanos(nanos);
        }
        // 添加
        enqueue(new Node<E>(e));
            // 元素个数加1(先返回后加)
        c = count.getAndIncrement();
        // 没满,放开写入限制
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        // 解锁
        putLock.unlock();
    }
    //  count原值为0时,才会去放开读限制
    if (c == 0)
        signalNotEmpty();
    return true;
}

添加,失败返回false

public boolean offer(E e) {
    // 添加空元素抛异常
    if (e == null) throw new NullPointerException();
    // 获取当前元素个数
    final AtomicInteger count = this.count;
    // 已满返回false
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    // 获取锁
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        // 未满添加
        if (count.get() < capacity) {
            enqueue(node);
            // 元素个数加1(先返回后加)
            c = count.getAndIncrement();
            // 未满,放开写限制
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        // 解锁
        putLock.unlock();
    }
    // count原值为0时,才会去放开读限制
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}

实际添加

private void enqueue(Node<E> node) {
    // 链表尾部添加元素
    last = last.next = node;
}

 

LinkedBlockingQueue 出队
出队,空则等待

public E take() throws InterruptedException {
    E x;
    int c = -1;
    // 元素个数
    final AtomicInteger count = this.count;
    // 获取读锁
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        // 元素个数等于0则等待
        while (count.get() == 0) {
            notEmpty.await();
        }
        // 实际出队
        x = dequeue();
        // 元素个数减1(先返回后减)
        c = count.getAndDecrement();
        // 未空,放开读限制
        if (c > 1)
            notEmpty.signal();
    } finally {
        // 解锁
        takeLock.unlock();
    }
    //  count原值为capacity时,才会去放开写限制
    if (c == capacity)
        signalNotFull();
    return x;
}

出队,空则等待,超时退出

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    E x = null;
    int c = -1;
    // 超时时间
    long nanos = unit.toNanos(timeout);
    // 元素个数
    final AtomicInteger count = this.count;
    // 获取读锁
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        // 元素个数等于0则等待
        while (count.get() == 0) {
            // 等待时间 小于0退出
            if (nanos <= 0)
                return null;
            // awaitNanos超时,则返回值小于等于0
            nanos = notEmpty.awaitNanos(nanos);
        }
        // 出队
        x = dequeue();
        // 元素个数减1(先返回后减)
        c = count.getAndDecrement();
        // 未空,放开读限制
        if (c > 1)
            notEmpty.signal();
    } finally {
        // 解锁
        takeLock.unlock();
    }
    //  count原值为capacity时,才会去放开写限制
    if (c == capacity)
        signalNotFull();
    return x;
}

出队,空则返回null

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();
            // 元素个数减1(先返回后减)
            c = count.getAndDecrement();
            // 未空,放开读限制
            if (c > 1)
                notEmpty.signal();
        }
    } finally {
        // 解锁
        takeLock.unlock();
    }
    //  count原值为capacity时,才会去放开写限制
    if (c == capacity)
        signalNotFull();
    return x;
}

实际出队操作

private E dequeue() {
    // 头节点指向下一个节点,原头节点清空
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h; // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}

 

LinkedBlockingQueue 删除元素

public boolean remove(Object o) {
    // 空元素返回false
    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;
    if (last == p)
        last = trail;
    // 原来是满的,就放开写限制
    if (count.getAndDecrement() == capacity)
        notFull.signal();
}

 

LinkedBlockingQueue 是否包含

public boolean contains(Object o) {
    // 空元素返回false
    if (o == null) return false;
    // 获取双锁
    fullyLock();
    try {
        // 遍历元素
        for (Node<E> p = head.next; p != null; p = p.next)
            // 查找一样的元素
            if (o.equals(p.item))
                return true;
        return false;
    } finally {
        // 释放双锁
        fullyUnlock();
    }
}

 

LinkedBlockingQueue 清空

public void clear() {
    // 获取双锁
    fullyLock();
    try {
        // 遍历链表
        for (Node<E> p, h = head; (p = h.next) != null; h = p) {
            // 清空所有元素
            h.next = h;
            p.item = null;
        }
        head = last;
        // 原来是满的,就放开写限制
        if (count.getAndSet(0) == capacity)
            notFull.signal();
    } finally {
        // 释放双锁
        fullyUnlock();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源码猎人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值