线程---BlockingQueue

25 篇文章 0 订阅

BlockingQueue

  • 什么是阻塞队列???
     阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。这两个附加的操作支持阻塞
    的插入和移除方法。
    1)支持阻塞的插入方法:在队列满的情况下添加元素会被阻塞,直至队列不满可以添加成功才能返回(put);
    2)支持阻塞的移除方法:在删除元素时,队列为空时删除操作会被阻塞,直至队列中有元素存在被删除是成功返回(take);
  • 应用场景:
     阻塞队列常用于生产者和消费者的场景,生产者是向队列里添加元素的线程,消费者是
    从队列里取元素的线程。阻塞队列就是生产者用来存放元素、消费者用来获取元素的容器。
  • BlockingQueue存在包:
     BlockingQueue接口及其实现类存在package java.util.concurrent包路径下;
  • 在阻塞队列不可用时,这两个附加操作提供了4种处理方式:
方法/处理方式抛出异常返回特殊值一直阻塞超时退出
插入add(e)offer(e)put(e)offer(e, time, unit)
移除remove()poll()take()poll(time, unit)
检查element()peek()不可用不可用

(1)抛出异常:当队列满时,如果再往队列里插入元素,会抛出IllegalStateException(“Queue
full”)异常。当队列空时,从队列里获取元素会抛出NoSuchElementException异常。
(2)返回特殊值:当往队列插入元素时,会返回元素是否插入成功,成功返回true。如果是移
除方法,则是从队列里取出一个元素,如果没有则返回null。
(3)一直阻塞:当阻塞队列满时,如果生产者线程往队列里put元素,队列会一直阻塞生产者
线程,直到队列可用或者响应中断退出。当队列空时,如果消费者线程从队列里take元素,队
列会阻塞住消费者线程,直到队列不为空。
(4)超时退出:当阻塞队列满时,如果生产者线程往队列里插入元素,队列会阻塞生产者线程
一段时间,如果超过了指定的时间,生产者线程就会退出。

Java 中的阻塞队列
  • JDK提供了7个阻塞队列如下:
ArrayBlockingQueue:一个由数组结构组成的有界阻塞队列。

LinkedBlockingQueue:一个由链表结构组成的有界阻塞队列。

SychronousQueue:同步阻塞队列,SynchronousQueue:一个不存储元素的阻塞队列。

PriorityBlockingQueue:一个支持优先级排序的无界阻塞队列。

DelayQueue:一个使用优先级队列实现的无界阻塞队列。

LinkedTransferQueue:一个由链表结构组成的无界阻塞队列。

LinkedBlockingDeque:一个由链表结构组成的双向阻塞队列。
ArrayBlockingQueue

从源码剖析一下ArrayBlockingQueue(JDK1.7)。ArrayBlockingQueue是一个用数组实现的有界阻塞队列。此队列按照先进先出(FIFO)的原则对元素进行排序。

  • 存在包:
     package java.util.concurrent;
  • 继承关系:
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable
  • 基本属性:
/** The queued items */底层实现使用数组来存储元素。
    final Object[] items;
	

    /** items index for next take, poll, peek or remove */读取操作的位置
    int takeIndex;

    /** items index for next put, offer, or add */写操作的位置
    int putIndex;

    /** Number of elements in the queue */队列中元素个数
    int count;

    /** Main lock guarding all access */队列同步相关属性
    final ReentrantLock lock;
    /** Condition for waiting takes */
    private final Condition notEmpty;//用来生产者和消费者之间通信
    /** Condition for waiting puts */
    private final Condition notFull;
  • 构造方法:
//通过capacity来初始化阻塞队列大小
	public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

     //通过capacity来初始化队列大小,fair设置锁的公平性和非公平性
   public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

     //用集合来初始化BlockingQueue
    public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }
  • Put()方法:
public void put(E e) throws InterruptedException {
        checkNotNull(e);//ArrayBlockingQueue中不能存储NUll值
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
    	//显性添加可中断锁
        try {
            while (count == items.length)
                notFull.await();
            //队列满了则处于await()等待状态,在take()操作中会给当前发送消息
            insert(e);
        } finally {
            //显性释放锁
            lock.unlock();
        }
    }
 private void insert(E x) {
        items[putIndex] = x;
        putIndex = inc(putIndex);
        ++count;
        notEmpty.signal();//作用于take()下,阻塞队列中元素为空await操作
    }
final int inc(int i) {
        return (++i == items.length) ? 0 : i;
    }


public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();//中断锁
        try {
            while (count == 0)
                notEmpty.await();//wait()
            return extract();
        } finally {
            lock.unlock();
        }
    }
private E extract() {
        final Object[] items = this.items;
        E x = this.<E>cast(items[takeIndex]);
        items[takeIndex] = null;
        takeIndex = inc(takeIndex);
        --count;
        notFull.signal();//作用于put操作中,队列满时的await
        return x;

  • take():
public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return extract();
        } finally {
            lock.unlock();
        }
    }
  • 对比ArrayBlockingQueue与LinkedBlockingQueue的区别???
ArrayBlockingQueue
底层数据结构:数组                     
一把锁                 

    /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */

    /** Main lock guarding all access */
    final ReentrantLock lock;
    /** Condition for waiting takes */
    private final Condition notEmpty;
    /** Condition for waiting puts */
    private final Condition notFull;

LinkedBlockingQueue:
底层数据结构:链表
两把锁
    /** Lock held by take, poll, etc */
    private final ReentrantLock takeLock = new ReentrantLock();

    /** Wait queue for waiting takes */
    private final Condition notEmpty = takeLock.newCondition();

    /** Lock held by put, offer, etc */
    private final ReentrantLock putLock = new ReentrantLock();

    /** Wait queue for waiting puts */
    private final Condition notFull = putLock.newCondition();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值