java并发队列之LinkedBlockingQueue(三)

java并发队列之LinkedBlockingQueue(三)

LinkedBlockingQueue是一个用单链表实现的有界阻塞并发安全队列.

实战

public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {

        final BlockingQueue<String> deque = new LinkedBlockingDeque<>(10);

        Runnable producerRunnable = new Runnable() {
            int i = 0;

            public void run() {
                while (true) {
                    i++;
                    try {
                        log.info("我生产了一个===" + i);
                        deque.put(i + "dddd");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Runnable customerRunnable = new Runnable() {
            public void run() {
                while (true) {
                    try {
                        log.info("我消费了一个===" + deque.take());
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread thread1 = new Thread(producerRunnable);
        thread1.start();

        Thread thread2 = new Thread(customerRunnable);
        thread2.start();
    }
}

LinkedBlockingQueue特性

  • LinkedBlockingQueue是使用单向链表实现的.
  • 使用共享锁(其实就是两把锁),压入队列和弹出队列是两把锁,这样多个线程可以同时操作队列.读写锁分离,也就是读写分离.
  • 只有当队列满了或者队列为空才会阻塞.
  • 先进先出队列
  • LinkedBlockingQueue是一个可选有界无界队列.当初始化LinkedBlockingQueue时不设置队列大小则为无界,设置了大小则为有界.
  • 队列头读取,队列尾插入操作.

源码分析

初始化

    //读取锁
    private final ReentrantLock takeLock = new ReentrantLock();

    //读取时等待
    private final Condition notEmpty = takeLock.newCondition();

    //写锁
    private final ReentrantLock putLock = new ReentrantLock();

    //写时等待
    private final Condition notFull = putLock.newCondition();
    
    //如果不设置队列大小,则默认为最大队列,无界队列
    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }

    //初始化队列大小,有界队列.
    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }
    

读取和写入是两把锁.说明读取时任然可以写.这里可以和ArrayBlockingQueue做为对比,ArrayBlockingQueue写的时候不能读,读的时候不能写,因为读写是一把锁,多个线程时只有一个线程能操作队列.

压入队列put阻塞方法

public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException(); 
        int c = -1;
        Node<E> node = new Node(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) {
        last = last.next = node;
    }

压入队列offer,add非阻塞方法

public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            //可以看到只有总数小于队列的时候才能做插入操作,但是又不阻塞.
            if (count.get() < capacity) {
                enqueue(node);
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        //take方法中,队列为空时被阻塞了,这里添加了一个元素后,唤醒被阻塞的线程
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }

这里和ArrayBlockingQueue是一个意思,就是offer,add方法虽然不阻塞,但是也不添加到队列里面,而是直接返回false.等同于你调用该方法无效一样

弹出队列take

public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
        	  //队列为空时阻塞
            while (count.get() == 0) {
                notEmpty.await();
            }
            x = dequeue();
            //出队列后-1
            c = count.getAndDecrement();
            //假如有5线程同时take,队列都为空,被5个take都被阻塞了.put成功后会唤醒其中一个take.被唤醒的第一个take1可以往下执行了,但是另外4个take还被阻塞呢,谁来唤醒它们呢?就是在这里被唤醒的.这里c>1说明队列里面有多个值了,执行唤醒动作,唤醒了take2.take2被唤醒后得以往下执行,同样的发现c>1,接着唤醒take3以此类推.
             if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        //c+1之后还等于总队列长度,说明队列里面至少有一个空位置,这个时候唤醒被阻塞的put操作.
        if (c == capacity)
            signalNotFull();
        return x;
    }

移除remove

		public boolean remove(Object o) {
        if (o == null) return false;
        //读写锁全部加锁
        fullyLock();
        try {
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (o.equals(p.item)) {
                    unlink(p, trail);
                    return true;
                }
            }
            return false;
        } finally {
            fullyUnlock();
        }
    }
    
    void fullyLock() {
        putLock.lock();
        takeLock.lock();
    }

    /**
     * Unlock to allow both puts and takes.
     */
    void fullyUnlock() {
        takeLock.unlock();
        putLock.unlock();
    }

可以看出,remove移除一个元素时,还是需要双重加锁的.读写这个时候都需要加锁

LinkedBlockingQueue的内部是通过单向链表实现的,使用头、尾节点来进行入队和出队操作,也就是入队操作都是对尾节点进行操作,出队操作都是对头节点进行操作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值