BlockQueue

用法

Queue也就是队列,只能有两种基本的操作,在头部取走一个元素和在尾部增加一个元素,所以是一种FIFO结构(先进先出),不同于栈,栈是一种后进先出的数据结构。

阻塞Queue常用的方法:

  • add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常

  • remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常

  • element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常

  • offer 添加一个元素并返回true 如果队列已满,则返回false

  • poll 移除并返问队列头部的元素 如果队列为空,则返回null

  • peek 返回队列头部的元素 如果队列为空,则返回null

  • put 添加一个元素 如果队列满,则阻塞

  • take 移除并返回队列头部的元素 如果队列为空,则阻塞

    其中poll和take都是取走队列头部的元素,区别在于take是阻塞的,如果take的时候,队列为空,那么调用take方法的线程会一直阻塞知道队列元素不为空就会被唤醒,而poll不是阻塞的,poll方法只会检查此刻队列的状态,若为空则返回null。

    同理put和offer也是同一个道理。

应用

阻塞队列对应的是生产者消费者模型,在线程池中有所应用,线程池的内部就是一个阻塞队列,生产者往里面增加任务,而消费者也就是线程池中的线程就会不断地从阻塞队列中取出任务然后消费。

BlockQueue有两种一种是基于数组这种数据结构的ArrayBlockQueue,另外一种是基于链表LinkedBlockQueue。

源码

首先BlockQueue是线程安全的,其内部有一个ReentrantLock,由ReentrantLock产生两个Condition,其中一个Condition是调用take方法阻塞的线程集合,另外一个是调用put方法阻塞线程的集合,我们知道ReentrantLock是基于AQS,那么Condition就是对这些阻塞线程操作的封装,主要用于阻塞线程和唤醒在队列中等待线程。

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

首先lock加锁,然后循环检查队列中元素的个数,若为0则阻塞,若不为0,则返回一个元素并删除,dequeue的具体细节和用不同的数据结构实现是不一样的,BlcokQueue一般有基于数组数据结构实现,也有基于链表数据结构实现的。

其他的方法看了下都累死,都是检查状态,要不阻塞,要不执行成功。

一个对比

阻塞队列是线程安全的,那么我们和LinkedList来做一个对比,LinkedList不是线程安全的,程序就是几个不同的线程不断的在尾部增加1000个元素:

public class BlockQueueTest {

    private LinkedBlockingQueue<Integer> collection;

    private CountDownLatch countDownLatch;

    public BlockQueueTest(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
        collection = new LinkedBlockingQueue<Integer>();
    }

    private void addElement(final int ele) {
        for (int i = 0 ; i < 10; i ++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000000; j ++)
                        collection.add(ele);

                    System.out.println(Thread.currentThread().getName() + " finish");
                    countDownLatch.countDown();
                }
            }.start();
        }
    }

    public LinkedBlockingQueue<Integer> getCollection() {
        return collection;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        BlockQueueTest test = new BlockQueueTest(countDownLatch);
        test.addElement(10);
        countDownLatch.await();
        System.out.println(test.getCollection().size());
    }


}

运行结果是:

Thread-5 finish
Thread-4 finish
Thread-2 finish
Thread-3 finish
Thread-7 finish
Thread-6 finish
Thread-9 finish
Thread-0 finish
Thread-1 finish
Thread-8 finish
10000000

若使用LinkedList来测试:

public class BlockQueueTest {

    private LinkedList<Integer> collection;

    private CountDownLatch countDownLatch;

    public BlockQueueTest(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
        collection = new LinkedList<Integer>();
    }

    private void addElement(final int ele) {
        for (int i = 0 ; i < 10; i ++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000000; j ++)
                        collection.add(ele);

                    System.out.println(Thread.currentThread().getName() + " finish");
                    countDownLatch.countDown();
                }
            }.start();
        }
    }

    public LinkedList<Integer> getCollection() {
        return collection;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        BlockQueueTest test = new BlockQueueTest(countDownLatch);
        test.addElement(10);
        countDownLatch.await();
        System.out.println(test.getCollection().size());
    }


}

测试结果:

Thread-5 finish
Thread-4 finish
Thread-1 finish
Thread-2 finish
Thread-0 finish
Thread-6 finish
Thread-9 finish
Thread-3 finish
Thread-8 finish
Thread-7 finish
1294411

由于不是线程安全的,最终集合中的元素不是我们预期的10000000

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值