java阻塞队列介绍(jdk 1.8)

BlockQueue提供的相关操作和特点:
方法/处理方式
抛出异常
返回特殊值
一直阻塞
超时退出
插入
add(e)
offer(e)
put(e)
offer(e,time,unit)
删除
remove()
poll()
take()
poll(time,unit)
检查
element()
peek()
 
ArrayBlockingQueue
数组实现的有界阻塞队列
LinkedBlockingQueue
链表实现的有界阻塞队列
PriorityBlockingQueue
支持优先级排序的无界阻塞队列
DelayQueue
优先级队列实现的无界阻塞队列
SynchronousQueue
不存储元素的阻塞队列
LinkedTransferQueue
链表实现的无界阻塞队列
LinkedBlockingDeque
链表实现的双向阻塞队列

   ArrayBlockingQueue 源码分析:

1 add(e)

 public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

 offer 插入成功后返回false,如果不成功说明队列已满,抛出异常。

2 offer(e)

 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();
        }
    }

 

如果e为空抛出空指针异常,先获得锁,如果队列已满返回false,否则加入队列。

 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();
    }

 一开始putIndex = 0,0赋值之后,和length,即创建队列制定的长度比对,相等说明队列满了,count为实际元素的个数,触发队列不为空事件。

 

3 put(e)

 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();
        }
    }

 当队列已满时,等待。 其他操作类似。

猜你喜欢

转载自edgar108.iteye.com/blog/2283253