DelayQueue是Java中基于优先级队列实现的无界阻塞队列,用于存放Delayed对象,按延迟时间排序,仅当延迟到期后才能取出,适用于定时任务、缓存过期等场景。

DelayQueue 是 Java 并发包 java.util.concurrent 中的一个无界阻塞队列,用于存放实现了 Delayed 接口的对象。只有当对象的延迟时间到达后,才能从队列中取出。这个特性让它非常适合用来实现定时任务调度、缓存过期处理、消息延迟消费等场景。
DelayQueue 的工作原理
DelayQueue 内部基于优先级队列(PriorityQueue)实现,元素按照延迟时间排序,延迟时间最短的排在队首。它只允许放入实现了 Delayed 接口的对象。该接口继承自 Comparable,需要实现两个方法:
- getDelay(TimeUnit unit):返回当前对象剩余的延迟时间。
- compareTo(Delayed other):比较当前对象与另一个对象的延迟时间,用于排序。
只有当 getDelay() 返回值小于等于 0 时,元素才能被 take() 取出。
创建 Delayed 对象
通常我们自定义一个类来实现 Delayed 接口。例如,表示一个延迟消息:
立即学习“Java免费学习笔记(深入)”;
public class DelayedMessage implements Delayed {
private String message;
private long executeTime; // 执行时间戳(毫秒)
public DelayedMessage(String message, long delayInMilliseconds) {
this.message = message;
this.executeTime = System.currentTimeMillis() + delayInMilliseconds;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = executeTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed other) {
return Long.compare(this.executeTime, ((DelayedMessage) other).executeTime);
}
public String getMessage() {
return message;
}}
DelayQueue 常用操作方法
以下是 DelayQueue 提供的核心方法及其用途:
- put(E e):将元素插入队列。由于是无界队列,不会阻塞。
- take():获取并移除队列中延迟到期的元素。如果队列为空或没有元素到期,线程会阻塞直到有元素可用。
- poll(long timeout, TimeUnit unit):尝试在指定时间内获取元素,超时返回 null。
- poll():非阻塞获取元素,仅当元素已到期才返回,否则返回 null。
- peek():查看但不移除队首元素(即使未到期也能看到),常用于调试。
使用示例:延迟任务执行
下面是一个简单的例子,演示如何使用 DelayQueue 实现延迟消息处理:
import java.util.concurrent.*;public class DelayQueueExample { public static void main(String[] args) throws InterruptedException { DelayQueue
queue = new DelayQueue<>(); // 添加几个延迟消息 queue.put(new DelayedMessage("消息1", 3000)); queue.put(new DelayedMessage("消息2", 5000)); queue.put(new DelayedMessage("消息3", 1000)); System.out.println("开始消费消息..."); // 消费者线程 while (!queue.isEmpty()) { DelayedMessage msg = queue.take(); // 阻塞等待到期 System.out.println("处理消息: " + msg.getMessage() + ",当前时间: " + System.currentTimeMillis()); } }}
输出结果会按延迟到期顺序打印消息,比如“消息3”最先被处理,尽管它最后加入。
基本上就这些。只要元素实现了 Delayed 接口,DelayQueue 就能自动管理其延迟逻辑。注意 DelayQueue 是线程安全的,适合多线程环境使用,但在高并发下要注意性能和 GC 影响。










