集合---阻塞队列

一,定义

java中的BlockingQueue接口是一个线程安全的存取队列,它提供四种不同的处理方法

阻塞队列定义:  队列插入的时候,当队列满时,队列会阻塞插入元素的线程,直到队列不满。

                           队列元素移除的时候,如果队列是空的,那么会等待队列有元素的时候,再移除。

上面四种情况,是面对队列满的时候,为空的时候,处理方案,不同场景使用不同的方案。

 

jdk7提供的7个阻塞队列

1.ArrayBlokingQueue:       底层是数组,有界

2.LinkedBlockingQueue:   链表组成,有界

3.PriorityBlockingQueue:  支持优先级排序的无界阻塞队列

4.DelayQueue:                 使用优先级队列实现的无界阻塞队列

5.SynchronousQueue:     不存储元素的阻塞队列

6.LinkedTransferQueue:  由链表组成的无界阻塞队列

7.LinkedBlockingDeque:  链表组成的双向队列    

 

二,具体实现                

1.第一组:数组+链表 有界祖肃

ArrayBlokingQueue  与 LinkedBlockingQueue

在线程池中称为无界,其实他们是有界的,因为最大值是Integer.Max_value,而这个值对于线程来说,实在是太多了,所以可以理解为无界。

他们与普通数组,链表的区别在于,他们线程安全,上锁操作,其次有阻塞操作。

重要字段:

final Object[] items;    //数组存放内容
int takeIndex;    //next poll index
int putIndex;    //next put index
int count;        //元素数量
final ReentrantLock lock;        //可重入锁
private final Condition notEmpty;    //是否空
private final Condition notFull;    //是否满

构造方法:

没有无参构造,必须提供数组的大小。

public ArrayBlockingQueue(int capacity): // 初始化数组大小
public ArrayBlockingQueue(int capacity, boolean fair): //初始化数组大小,并且设定是否是fire模式
public ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c) //初始化数组大小,设置是否是fair模式,然后使用一个集合初始化阻塞队列

fair参数是指,是否公平,阻塞的线程能否公平的访问队列。公平值,访问队列的顺序根据先来后到的顺序。

    创建之后,容量是不能改变的,默认使用非公平模式

1.1 put()方法 添加元素

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == items.length)
            notFull.await();    //阻塞
        enqueue(e);    //添加
    } finally {
        lock.unlock();
    }
}

添加元素

private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x;    //放入
    if (++putIndex == items.length)
        putIndex = 0;    //循环放入
    count++;
    notEmpty.signal();    //唤醒空等待
}

1.2 take()方法

弹出元素,与Put()成一组,都是阻塞方法

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}

逻辑与put()相似

private E dequeue() {
    // assert lock.getHoldCount() == 1;
    // assert items[takeIndex] != null;
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex];
    items[takeIndex] = null;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    notFull.signal();
    return x;
}

1.3 offer()加入

    直接返回成功与否,不会阻塞

public boolean offer(E e) {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count == items.length)
            return false;
        else {
            enqueue(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

还有很多方法,这里就不一一例举了,可以参考下方第二个链接。

LinkedBlockingQueue

    底层链表实现,自然使用到节点Node

static class Node<E> {
    E item;
    Node<E> next;
    Node(E x) { item = x; }
}

字段:

private final int capacity;        //链表容量,默认Integer.Max_Value
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();

2.1 put()方法

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);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

添加节点,比较简单:

private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    last = last.next = node;
}

2.第二组,优先级无界阻塞队列

PriorityBlockingQueue 和 DelayQueue

PriorityBlockingQueue默认情况下,采取自然的顺序升序排列,也可以自定义compareTo()方法来指定元素排序规则

DelayQueue: 支持延时获取元素的无界阻塞队列,队列使用PriorityQueue来实现的。它可以用到缓冲系统的设计,定时任务调度。

 

3.第三组,链表组成的无界与双向 阻塞队列

LinkedTransferQueue 和 LinkedBlockingDeque

 

 

参考链接:

1.https://blog.csdn.net/gaotiedun1/article/details/86606135

2.https://www.jianshu.com/p/4028efdbfc35(简书)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值