BlockingQueue---BlockingDeque

发布时间 2023-11-01 15:02:53作者: anpeiyong

概述

A {@link Deque} that additionally supports blocking operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element.

Deque支持阻塞操作:当获取元素时 会等待Deque变成非空; 当存储元素时 会等待Deque变可用;

 

{@code BlockingDeque} methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future:
one throws an exception,
the second returns a special value (either {@code null} or {@code false}, depending on the operation),
the third blocks the current thread indefinitely until the operation can succeed,
and the fourth blocks for only a given maximum time limit before giving up.

BlockingDeque方法有4种形式:

1、抛异常

2、依赖不同的操作,返回null或false;

3、阻塞当前线程直到操作成功

4、阻塞直到timeout放弃

 

Like any {@link BlockingQueue}, a {@code BlockingDeque} is thread safe, does not permit null elements, and may (or may not) be capacity-constrained.

BlockingDeque是线程安全的,不允许null,可能也有容量限制;

 

一个双端队列

在不能够插入元素时,它将阻塞住试图插入元素的线程;在不能够抽取元素时,它将阻塞住试图抽取的线程。

deque(双端队列) 是 "Double Ended Queue" 的缩写。

因此,双端队列是一个你可以从任意一端插入或者抽取元素的队列

 

使用场景

1、线程既是一个队列的生产者又是这个队列的消费者的时候可以使用到 BlockingDeque。

2、如果生产者线程需要在队列的两端都可以插入数据,消费者线程需要在队列的两端都可以移除数据,这个时候也可以使用 BlockingDeque;