JUC中多线程的集合——ArrayBlockingQueue和LinkedBlockingQueue和DelayedWorkQueue

部分摘抄自

https://blog.csdn.net/javazejian/article/details/77410889?locationNum=1&fps=1#linkedblockingqueue%E5%92%8Carrayblockingqueue%E8%BF%A5%E5%BC%82

阻塞队列

BlockingQueue是JUC中的接口。JUC同时也提供了一些实现。比如本文要探讨的ArrayBlockingQueue,LinkedBlockingQueue,DelayedWorkQueue

在JDK中,LinkedList或ArrayList就是队列。但是实际使用者并不多。
阻塞队列与我们平常接触的普通队列(LinkedList或ArrayList等)的最大不同点,在于阻塞队列支出阻塞添加和阻塞删除方法。

  • 阻塞添加
    所谓的阻塞添加是指当阻塞队列元素已满时,队列会阻塞加入元素的线程,直队列元素不满时才重新唤醒线程执行元素加入操作。

  • 阻塞删除
    阻塞删除是指在队列元素为空时,删除队列元素的线程将被阻塞,直到队列不为空再执行删除操作(一般都会返回被删除的元素)

这里写图片描述

ArrayBlockingQueue

首先我们看一下如何使用

private final static ArrayBlockingQueue<Apple> mAbq= new ArrayBlockingQueue<>(1);
//生产者代码
Apple apple = new Apple();
mAbq.put(apple);
//消费者代码
Apple apple = mAbq.take();
System.out.println("消费Apple="+apple);

在构造方法中

    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        //首先初始化本对象用的锁。如果设置为公平锁,则先lock的线程先获取到锁。
        //公平锁会带来性能损失
        //synchronized是非公平锁,ReentrantLock在默认的情况下也是非公平锁
        lock = new ReentrantLock(fair);
        //Conditon中的await()对应Object的wait();
		//Condition中的signal()对应Object的notify();
		//Condition中的signalAll()对应Object的notifyAll()。
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

首先,我们先看看阻塞的put和take方法。首先,是对

    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();//加锁,可以被别的线程打断
        try {
            while (count == items.length)
                notFull.await();//如果队列已经满了,则等待(调用await就等于释放了锁)
            enqueue(e);
        } finally {
            lock.unlock();//多说一句,lock一定要记得在finally中unlock。和JVM支持的synchronized关键字不同,一旦发生异常而你没有unlock,则锁一直会被锁死。
            
        }
    }

   public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)//如果队列为空,则等待
                notEmpty.await();
            return dequeue();
        } 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();
    }

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

LinkedBlockingQueue

唯一的区别是出兑入队换成了对链表的操作。

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

    private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        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;
    }

DelayedWorkQueue

这个类实现在ScheduledThreadPoolExecutor中
该队列是定制的优先级队列,只能用来存储RunnableScheduledFutures任务。堆是实现优先级队列的最佳选择,而该队列正好是基于堆数据结构的实现。

该类也维护一个lock和一个Condition


        private final ReentrantLock lock = new ReentrantLock();

        /**
         * Condition signalled when a newer task becomes available at the
         * head of the queue or a new thread may need to become leader.
         */
        private final Condition available = lock.newCondition();
        

还设定了一个领袖线程

        /**
         * Thread designated to wait for the task at the head of the
         * queue.  This variant of the Leader-Follower pattern
         * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
         * minimize unnecessary timed waiting.  When a thread becomes
         * the leader, it waits only for the next delay to elapse, but
         * other threads await indefinitely.  The leader thread must
         * signal some other thread before returning from take() or
         * poll(...), unless some other thread becomes leader in the
         * interim.  Whenever the head of the queue is replaced with a
         * task with an earlier expiration time, the leader field is
         * invalidated by being reset to null, and some waiting
         * thread, but not necessarily the current leader, is
         * signalled.  So waiting threads must be prepared to acquire
         * and lose leadership while waiting.
         */
        private Thread leader = null;

我们看一下offer方法

        public boolean offer(Runnable x) {
            if (x == null)
                throw new NullPointerException();
            RunnableScheduledFuture<?> e = (RunnableScheduledFuture<?>)x;
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                int i = size;
                if (i >= queue.length)
                    grow();
                size = i + 1;
                if (i == 0) {
                    queue[0] = e;
                    setIndex(e, 0);
                } else {
                    //将数据e插入底层数组,然后调整堆结构
                    siftUp(i, e);
                }
                if (queue[0] == e) {//如果当前元素已经是堆顶,那么发出信号
                    leader = null;
                    available.signal();
                }
            } finally {
                lock.unlock();
            }
            return true;
        }

我们看下task方法

        public RunnableScheduledFuture<?> take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                for (;;) {
                    RunnableScheduledFuture<?> first = queue[0];
                    if (first == null)//如果是空则等待
                        available.await();
                    else {
                        long delay = first.getDelay(NANOSECONDS);//获取现在还剩下的延迟时间
                        if (delay <= 0)
                            return finishPoll(first);//出堆
                        first = null; // don't retain ref while waiting
                        if (leader != null)//如果leader线程的位置已经被抢占了
                            available.await();
                        else {
                            //把自己指定为leader线程,并在delay倒是被唤醒。唤醒后会循环去取
                            Thread thisThread = Thread.currentThread();
                            leader = thisThread;
                            try {
                                available.awaitNanos(delay);
                            } finally {
                                if (leader == thisThread)
                                    leader = null;
                            }
                        }
                    }
                }
            } finally {
                //只有取到数据的人才会走到这里,释放锁
                if (leader == null && queue[0] != null)
                    available.signal();
                lock.unlock();
            }
        }

二者异同

1.队列大小有所不同,ArrayBlockingQueue是有界的初始化必须指定大小,而LinkedBlockingQueue可以是有界的也可以是无界的(Integer.MAX_VALUE),对于后者而言,当添加速度大于移除速度时,在无界的情况下,可能会造成内存溢出等问题。

2.数据存储容器不同,ArrayBlockingQueue采用的是数组作为数据存储容器,而LinkedBlockingQueue采用的则是以Node节点作为连接对象的链表。

3.由于ArrayBlockingQueue采用的是数组的存储容器,因此在插入或删除元素时不会产生或销毁任何额外的对象实例,而LinkedBlockingQueue则会生成一个额外的Node对象。这可能在长时间内需要高效并发地处理大批量数据的时,对于GC可能存在较大影响。

4.两者的实现队列添加或移除的锁不一样,ArrayBlockingQueue实现的队列中的锁是没有分离的,即添加操作和移除操作采用的同一个ReenterLock锁,而LinkedBlockingQueue实现的队列中的锁是分离的,其添加采用的是putLock,移除采用的则是takeLock,这样能大大提高队列的吞吐量,也意味着在高并发的情况下生产者和消费者可以并行地操作队列中的数据,以此来提高整个队列的并发性能。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值