阻塞queue系列之DelayQueue

本文深入解析了Java并发包中的DelayQueue,介绍了其构造方法、工作原理及底层实现方式。此外,还详细阐述了如何通过实现Delayed接口来定制元素的延迟时间,并提供了一个具体的使用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DelayQueue是一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部是延迟期满后保存时间最长的Delayed 元素。底层也是通过数组实现,所以读写操作使用的是同一把锁,其插入的元素必须实现Delayed接口。

构造方法

public DelayQueue() {}

public DelayQueue(Collection<? extends E> c) {
        this.addAll(c);
    }

Delayed接口

public interface Delayed extends Comparable<Delayed> {

    long getDelay(TimeUnit unit);
}

Delayed接口继承了Comparable接口,所以当我们插入的元素实现Delayed接口时,须实现两个方法getDelay(TimeUnit unit)和compareTo(Delayed o),这两个方法将在下面源码中介绍。

常用方法

  • offer 添加元素
    这里写图片描述
    这里写图片描述

其中q是PriorityQueue q = new PriorityQueue(); 可见其实现是通过PriorityQueue实现。

add和put都是调用offer方法,他们三者无任何区别,添加元素都是立刻添加的,无延迟。

siftUp(i, e) 里面是什么呢?
这里写图片描述
看到这里是不是感觉熟悉,是的这里类似PriorityBlockingQueue,因为comparator为null, 会使用插入元素实现了Comparatable接口的方法进行比较,按照顺序插入。(解释了compareTo(Delayed o)方法)


  • peek 取第一个元素,不会删除

这里写图片描述
可见,和其它阻塞队列的peek方法一样,也是立刻取值,并不延迟。


  • poll 取元素
    这里写图片描述

first.getDelay(NANOSECONDS) > 0 可以看出,当取的元素是null或者未到期时,这时就会返回null.
getDelay方法就是接口Delayed接口的方法,也就是插入元素的方法(插入元素实现Delayed接口)。(解释了getDelay(TimeUnit unit)方法)。


  • take 取元素

这里写图片描述

take方法会阻塞,直到待取元素已经到期了。

案例

public class DelayQueueExample {
    private DelayQueue<DelayElement> queue;

    @Before
    public void Before() {
        queue = new DelayQueue();
    }

    @Test
    public void test() throws InterruptedException {
        queue.add(DelayElement.of("hello",TimeUnit.SECONDS,1));
        System.out.println(queue.size());
        //peek无延迟
        System.out.println(queue.peek());
        //若时间未到,返回null,若时间已到,取值
        System.out.println(queue.poll());
        //take延迟,阻塞至取到值
        System.out.println(queue.take().getE());
    }



    static class DelayElement<E> implements Delayed{
        private final E e;
        private final long dealy;

        DelayElement(E e, TimeUnit unit,long dealy) {
            this.e = e;
            this.dealy = TimeUnit.MILLISECONDS.convert(dealy,unit) + System.currentTimeMillis();
        }

        static <T>DelayElement<T> of(T e, TimeUnit unit,long dealy){
            return new DelayElement(e,unit, dealy);
        }

        static <T>DelayElement<T> of(T e,long dealy){
            return new DelayElement(e,TimeUnit.MILLISECONDS, dealy);
        }
        @Override
        public long getDelay(TimeUnit unit) {
            long l = dealy - System.currentTimeMillis();
            return unit.convert(l,TimeUnit.MICROSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            DelayElement that = (DelayElement) o;
            if (this.dealy > that.getDealy()){
                return 1;
            } else if (this.dealy < that.getDealy()){
                return -1;
            } else {
                return 0;
            }
        }

        public E getE() {
            return e;
        }

        public long getDealy() {
            return dealy;
        }


        @Override
        public String toString() {
            return "DelayElement{" +
                    "e=" + e +
                    ", dealy=" + dealy +
                    '}';
        }
    }
}
### Java 中阻塞队列的使用及实现 #### 1. 阻塞队列的概念 阻塞队列是一种特殊的队列,在多线程环境下,当队列为空时尝试获取数据的操作会被阻塞;同样地,当队列已满时尝试插入数据的操作也会被阻塞。这种特性使得阻塞队列非常适合用于生产者-消费者模型中的线程间通信。 #### 2. 常见的 `BlockingQueue` 实现类及其特点 以下是几种常见的 `BlockingQueue` 实现: - **ArrayBlockingQueue**: 这是一个基于数组结构的有界阻塞队列,初始化时必须指定其容量大小[^1]。它是通过锁机制来保证线程安全性的。 - **LinkedBlockingQueue**: 它是一个基于链表结构的可选有界阻塞队列,默认情况下是无界的(即默认容量为 `Integer.MAX_VALUE`)。为了防止内存溢出,通常建议设置一个合理的上限[^2]。 - **PriorityBlockingQueue**: 支持优先级排序的无界阻塞队列,其中元素按照自然顺序或自定义比较器进行排列[^4]。 - **DelayQueue**: 只有延迟期满后的元素才能够从队列中取走的一种无界阻塞队列。 - **SynchronousQueue**: 不存储任何元素的特殊阻塞队列,每一个插入操作都必须等待另一个线程执行对应的移除操作。 #### 3. 核心方法 `BlockingQueue` 接口提供了多种核心方法以支持不同场景下的操作需求: - 抛异常的方法:如果试图在一个空队列上调用 `remove()` 或在满队列上执行 `add()`, 将会抛出 `IllegalStateException`。 - 返回特殊情况值的方法:如调用 `offer(null)` 方法返回 false 表明失败。 - 超时退出的方法:这些方法会在一定时间内无法完成相应动作则自动放弃并返回结果。 - 阻塞当前线程直到成功的方法:例如 `put(E e)` 和 `take()` 分别用来向队列放入对象以及从中取出对象,并且它们都会一直阻塞直至条件达成为止[^3]。 #### 4. 示例代码 (以 ArrayBlockingQueue 为例) 下面展示了一个简单的生产者-消费者模式的例子,利用了 `ArrayBlockingQueue` 来同步两个独立运行的任务之间的交互过程。 ```java import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerExample { public static void main(String[] args) throws InterruptedException { BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); Thread producerThread = new Thread(() -> { try { int value = 0; while (true) { System.out.println("Producing: " + value); queue.put(value++); Thread.sleep(1000); // Simulate delay in producing items. } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }); Thread consumerThread = new Thread(() -> { try { while (true) { Integer consumedValue = queue.take(); System.out.println("Consumed: " + consumedValue); Thread.sleep(2000); // Simulate longer processing time by consumers. } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }); producerThread.start(); consumerThread.start(); producerThread.join(); consumerThread.join(); } } ``` 此程序展示了如何创建固定长度的缓冲区并通过多个线程对其进行访问控制,从而实现了基本的数据流管理功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值