四、ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue和DelayQueue学习总结

Java并发编程之四大阻塞队列
本文深入探讨了Java并发编程中四种主要的阻塞队列:ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue和DelayQueue。详细介绍了它们的工作原理、构造函数以及在生产者-消费者模式中的应用实例。

一、JMM模型与volatile详解
二、synchronized原理详解
三、AQS框架详解——AbstractQueuedSynchronizer
四、ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue和DelayQueue学习总结
五、CountDownLatch、CyclicBarrier和Semaphore的比较
java中interruptor理解与使用
Java线程的6种状态及切换
MESI协议:保证可见性,无法保证原子性

BlockingQueue是juc包中解决并发生产者——消费者问题的最有用的类,它的特性是任意时刻只有一个线程可以进行take和put操作,并且提供了超时return null的机制。

(1)线程间通信工具
(2)线程安全,先入先出

BlockingQueue的常见API

put方法,将指定的元素插入队列,将会阻塞,直到有空间插入。

void put(E e) throws InterruptedException;

offer方法,在指定时间内如果插入成功,则返回true,否则返回false

boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;

take方法:获取队列的头部信息,并将其从队列中删除;如果为空,则阻塞操作,直到队列中有元素为止。

E take() throws InterruptedException;

poll方法:获取队列的头部信息,并将其从队列中删除,如果规定时间内没有元素,则返回null。

E poll(long timeout, TimeUnit unit)
        throws InterruptedException;

常见的四种阻塞队列

1、ArrayBlockingQueue:由数组支持的有界队列
2、LinkedBlockingQueue:由链表支持的可选有界队列
3、PriorityBlockingQueue:由优先级支持无界优先级队列
4、DelayQueue:由优先级堆支持的,基于时间的调度队列

一、ArrayBlockingQueue

队列基于数组实现,容量大小在创建的时候就已经定义好。

1、构造函数

 public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }
public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        //条件对象
        ///** Condition for waiting takes */
        notEmpty = lock.newCondition();
        ///** Condition for waiting puts */
        notFull =  lock.newCondition();
    }
   public final void await() throws InterruptedException {
            //线程是否已经被中断
            if (Thread.interrupted())
                throw new InterruptedException();
                //ConditionWaiter:条件等待队列
            Node node = addConditionWaiter();
            //释放锁
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            //判断是否在同步队列中,不在同步队列中,在条件队列中,阻塞该节点
            while (!isOnSyncQueue(node)) {

                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

工作原理:基于ReentrantLock保证线程安全,根据Condition实现队列满时的阻塞。

AQS:条件等待队列
队列满——入列——释放锁——唤醒

同步队列VS条件等待队列
获取锁的条件:CLH队列+singal
条件队列中不可以获取锁,条件满足才可以获取锁。

二、LinkedBlockingQueue

是基于链表的无界队列,理论上有界。

1、构造函数

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

根据构造函数,可以看到LinkedBlockingQueue的队列最大值为Integer.MAX_VALUE,向队列中添加元素,永远不会阻塞,但是如果队列过长,可能会导致OOM异常。

三、DelayQueue

内部基于无界队列PriorityQueue实现,而无界队列基于数组的扩容实现。

1、构造函数

public DelayQueue() {}

入队的对象必须要实现Delayed接口,而Delayed集成自Comparable接口

2、工作原理

队列内部会根据时间优先级进行排序。延迟类线程池周期执行。

四、生产者和消费者的例子

生产者生产1-100之间的数字放入到阻塞队列中,消费者取出数字;为了避免消费者无限等待下去,可以在队列中设置标志位,如果消费者消费到了标志位,消费者进程结束。

生产者

package com.ysy.多线程.生产者和消费者;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author shanyangyang
 * @date 2020/8/31
 */
public class NumberProducer implements Runnable {
    private BlockingQueue<Integer> numbersQueue;

    /**标志位,消费者遇到标志位就停止*/
    private final int flag;
    /**产生标志位的线程数目*/
    private final int flagProducer;

    public NumberProducer(BlockingQueue<Integer> numbersQueue, int flag, int flagProducer) {
        this.numbersQueue = numbersQueue;
        this.flag = flag;
        this.flagProducer = flagProducer;
    }

    @Override

    public void run() {
        try {
            generateNumbers();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void generateNumbers() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
            System.out.println("线程" + Thread.currentThread().getId() + "正在工作");
        }
        for (int i = 0; i < flagProducer; i++) {
            numbersQueue.put(flag);
            System.out.println("线程" + Thread.currentThread().getId() + "向队列中添加第" + i + "个flag");
        }
    }
}

消费者

package com.ysy.多线程.生产者和消费者;

import java.util.concurrent.BlockingQueue;

/**
 * @author shanyangyang
 * @date 2020/8/31
 */
public class NumberCustomer implements Runnable {
    private BlockingQueue<Integer> blockingQueue;
    private final int flag;

    public NumberCustomer(BlockingQueue<Integer> blockingQueue, int flag) {
        this.blockingQueue = blockingQueue;
        this.flag = flag;
    }

    @Override public void run() {
        while (true) {
            try {
                Integer num = blockingQueue.take();
                if (num.equals(flag)) {
                    System.out.println("消费者线程结束");
                    return;
                }
                System.out.println("消费者取出数字" + num);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

测试类

package com.ysy.多线程.生产者和消费者;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author shanyangyang
 * @date 2020/8/31
 */
public class Test {
    public static void main(String[] args) {
        //设置队列容量大小为
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(10);
        for (int i = 0; i < 16; i++) {
            new Thread(new NumberProducer(blockingQueue, Integer.MAX_VALUE, 4)).start();
        }
        for (int i = 0; i < 4; i++) {
            new Thread(new NumberCustomer(blockingQueue, Integer.MAX_VALUE)).start();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值