DelayQueue的使用

本文深入解析Java中延时队列DelayQueue的工作原理,通过实例演示如何使用该队列进行电影下载模拟,展示了如何定义Delayed类型的元素并实现getDelay方法计算剩余过期时间。

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

	DelayQueue,顾名思义,延时队列。放入队列的数据需设置超期时间,只有到达了超期时间后,

才能从队列取出。可以用于订单超时支付等场景。

1、首先我们看下DelayQueue,便于我们使用

public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
implements BlockingQueue<E>	

DelayQueue<E extends Delayed>,放入DelayQueue的数据必须是Delayed的类型的

如下,我们定义一个DelayedData类,并重写了Delayed 里面的getDelay方法,该方法主要用于
计算还剩多少时间过期。之所以定义一个泛型T,是因为传入我们DelayedData的数据类型不确定,
可能是任何对象(阿里代码开发规范指出,避免使用 Object做参数传递)。

@Data
public class DelayedData<T> implements Delayed {

	/**
     * 描述:过期时间
     */
    private Long expireTime;

    private T data;
    
    /**
     * 描述:构造方法
     * @param delayTime 过期时长
     * @param data 放入DelayQueue的真实数据
     */ 
    DelayedData(Long delayTime, T data){
        this.expireTime = System.currentTimeMillis() + delayTime;
        this.data = data;
    }

    /**
     * 描述:获取过期剩余时间
     * 时间为0 时,延时队列DelayQueue 才可以将它取出
     */ 
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expireTime - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed o) {
        return 0;
    }
}

我们来模拟下载电影的场景,电影下载需要时间,越大的电影下载时间越长。电影的下载时长就是在
DelayQueue的过期时长。

定义电影
@Data
public class SmallMovie {

    /**
     * 描述:电影类型
     */ 
    private String type;

    /**
     * 描述:电影大小
     */ 
    private Long size;

    SmallMovie(String type, Long size){
        this.type = type;
        this.size = size;
    }
}

测试类
@Data
public class MyDelayQueueTest{
    public static DelayQueue<DelayedData<SmallMovie>> delayQueue = new DelayQueue();

    public static void main(String[] args) throws InterruptedException {

        SmallMovie smallMovie = new SmallMovie("高清",102L);
        DelayedData delayedData = new DelayedData(5000L, smallMovie);
        delayQueue.add(delayedData);

        // 延时二十秒
        SmallMovie smallMovie1 = new SmallMovie("蓝光",402L);
        DelayedData delayedData1 = new DelayedData(20000L, smallMovie1);
        delayQueue.add(delayedData1);

        Integer count = 0;
        Long time = System.currentTimeMillis();
        while (true){
            SmallMovie myMovie = delayQueue.take().getData();
            System.out.println(myMovie);
            count ++;
            System.out.println((System.currentTimeMillis() - time)/1000 + "秒后成功下载第" + count + "部电影!");
        }
    }
}

当然,真实场景肯定是其他线程往delayQueue 里面不断地塞小电影,然后我们可能会有一条专门的线程去
不断地取。
需要的注意的是delayQueue.take()方法是阻塞方法,所以 while (true)不会太耗性能,因为只有take到了才能
继续往下走。
以下是DelayQueue的take()的源码,中间省略了一部分,可以看到队列的take(add也一样)方法使用了
可重入锁ReentrantLock 来保证安全性的。
	 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
             ...
            }
        } finally {
            if (leader == null && q.peek() != null)
                available.signal();
            lock.unlock();
        }
    }
### 关于 `DelayQueue` 的使用 #### Java 中的 `DelayQueue` `DelayQueue` 是一种特殊的无界阻塞队列,它仅允许插入延迟元素。只有当元素到期时才能从中提取这些元素。此接口通常用于实现诸如缓存清理服务、定时任务调度等功能。 ```java import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; class DelayedTask implements Delayed { private final long triggerTime; private final String taskName; public DelayedTask(String name, int delayInMilliseconds) { this.taskName = name; this.triggerTime = System.currentTimeMillis() + delayInMilliseconds; } @Override public long getDelay(TimeUnit unit) { long diff = triggerTime - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { if (this.getDelay(TimeUnit.MILLISECONDS) < ((Delayed)o).getDelay(TimeUnit.MILLISECONDS)) return -1; if (this.getDelay(TimeUnit.MILLISECONDS) > ((Delayed)o).getDelay(TimeUnit.MILLISECONDS)) return 1; return 0; } public void execute(){ System.out.println(taskName+" is executed at "+System.currentTimeMillis()); } } ``` 创建并启动一个线程来不断尝试从 `DelayQueue` 获取已过期的任务: ```java public class TaskScheduler { private static final DelayQueue<DelayedTask> queue = new DelayQueue<>(); public static void main(String[] args){ // 添加一些测试任务 queue.put(new DelayedTask("task-1", 2000)); queue.put(new DelayedTask("task-2", 4000)); Thread schedulerThread = new Thread(() -> { try{ while(true){ DelayedTask task = queue.take(); // 阻塞直到有可用的任务 task.execute(); } }catch(Exception e){ e.printStackTrace(); } }); schedulerThread.start(); } } ``` 上述代码展示了如何定义自定义的 `Delayed` 类型以及如何利用 `DelayQueue` 来管理它们。通过这种方式可以方便地构建基于时间触发的应用场景[^1]。 对于更复杂的业务需求,如分布式环境下的延时消息处理,则可能需要用到像 Redis 这样的外部存储系统配合特定框架完成相似功能[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值