阻塞队列BlockingQueue实战及其原理分析

1.BlockingQueue介绍

1. Queue(队列)顶层接口

add(E) 添加元素,成功返回true,否则返回异常

offer(E) 添加元素,成功返回true,否则返回false

remove() 返回并移除队首元素,队列为空返回异常

poll() 返回并移除队首元素,队列为空返回null

peek() 获取队首元素,队列为空则返回null

BlockingQueue继承于Queue,提供了阻塞的特性,入队和出队都有常用的方法

入队:put(E) offer(E) offer(E,long,TimeUnit)

出队:poll(),poll(long,TimeUnit),take()

1.1 BlockingQueue常用方法实战

演示常用四种方法:add remove offer poll使用,符合队列先进先出的特性。

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest {

    public static void main(String[] args) {

        //测试add remove offer poll
        Queue addblockingQueue = new ArrayBlockingQueue(2);
        addblockingQueue.add(1);
        addblockingQueue.add(2);
//        addblockingQueue.add(3);//放入第三个Exception in thread "main" java.lang.IllegalStateException: Queue full

//        addblockingQueue.remove();
//        addblockingQueue.remove();
//        addblockingQueue.remove();//移出第三个Exception in thread "main" java.util.NoSuchElementException

        Queue offerblockingQueue = new ArrayBlockingQueue(2);
        System.out.println(offerblockingQueue.offer(1));//返回true
        System.out.println(offerblockingQueue.offer(2));//返回true
        System.out.println(offerblockingQueue.offer(3));//返回false

        System.out.println(offerblockingQueue.poll());//返回1
        System.out.println(offerblockingQueue.poll());//返回1 符合队列特性先进先出
        System.out.println(offerblockingQueue.poll());//返回null
    }
}

1.2 常用的队列

队列的应用场景:队列是线程的安全的,我们经常在线程池,中间件比如生产者消费者模式和nacos注册中心中使用。 

1.2.1 ArrayBlockingQueue介绍(TODO)

 ArrayBlockingQueue是一个有界阻塞队列,底层基于数组实现,使用reenTrantLock来保证线程安全,一般情况下使用是一个不错的选择,但是在高并发场景下,因为用reenTrantLock加锁和解锁,插入和取出的速度会称为性能瓶颈,在高并发场景下一般使用linkedBlockingQueue,实战代码见1.1

源码分析关注点:

1.构造方法

2.使用的元素:数组,reenTrantLock,两个条件队列(没满和为空)

3.put和take方法

 1.2.2 linkedBlockingQueue介绍(TODO)

linkedBlockingQueue是一个链表实现的有界阻塞队列,但是它的默认最大值是Integer.MAX_VALUE,是一个很大的数字,所以我们经常说它是一个无界的阻塞队列。当内存不足时,会跑出OOM问题,所以为了解决这个问题,一般在初始化时就要指定队列的大小。linkedBlockingQueue也是使用的ReentrantLock来保证线程安全,与arrayBlockingQueue的区别也于它有两把锁,一把用于入队,一把用于出队,也有两个条件队列,保证入队和出队的唤醒。

源码分析关注点:

1.构造方法

2.使用的元素

3.put,take,remove方法

1.2.3 LinkedBlockingDeque介绍

Deque是一个阻塞双端队列,特性跟linkedBolckingQueue差不多,跟linkedBolckingQueue不同的是只有一把reentrantLock锁,多了几个API,能够操作队首和队尾元素。

addFirst(E e)
addLast(E e)
offerFirst(E e)
offerLast(E e)

 

猜你喜欢

转载自blog.csdn.net/qq_21575929/article/details/124774267
今日推荐