数据结构学习网站:
思维导图
DelayQueue (延时队列)
DelayQueue 是一个支持延时获取元素的阻塞队列
, 内部采用优先队列 PriorityQueue 存储元素,同时元素必须实现 Delayed 接口;在创建元素时可以指定多久才可以从队列中获取当前元素,只有在延迟期满时才能从队列中提取元素。
延迟队列的特点是:
不是先进先出,而是会按照延迟时间的 长短来排序,下一个即将执行的任务会排到队列的最前面。
它是无界队列,放入的元素必须实现 Delayed 接口,而 Delayed 接口又继承了 Comparable 接
口,所以自然就拥有了比较和排序的能力,代码如下:
public interface Delayed extends Comparable<Delayed> {
//getDelay 方法返回的是“还剩下多长的延迟时间才会被执行”,
//如果返回 0 或者负数则代表任务已过期。
//元素会根据延迟时间的长短被放到队列的不同位置,越靠近队列头代表越早过期。
long getDelay(TimeUnit unit);
}
DelayQueue使用
DelayQueue 实现延迟订单
在实现一个延迟订单的场景中,我们可以定义一个 Order 类,其中包含订单的基本信息,例如订单编 号、订单金额、订单创建时间等。同时,我们可以让 Order 类实现 Delayed 接口,重写 getDelay 和 compareTo 方法。在 getDelay 方法中,我们可以计算订单的剩余延迟时间,而在 compareTo 方法 中,我们可以根据订单的延迟时间进行比较。
下面是一个简单的示例代码,演示了如何使用 DelayQueue 来实现一个延迟订单的场景:
public class DelayQueueExample {
public static void main(String[] args) throws InterruptedException {
DelayQueue<Order> delayQueue = new DelayQueue<>();
// 添加三个订单,分别延迟 5 秒、2 秒和 3 秒
delayQueue.put(new Order("order1", System.currentTimeMillis(), 5000));
delayQueue.put(new Order("order2", System.currentTimeMillis(), 2000));
delayQueue.put(new Order("order3", System.currentTimeMillis(), 3000));
// 循环取出订单,直到所有订单都被处理完毕
while (!delayQueue.isEmpty()) {
Order order = delayQueue.take();
System.out.println("处理订单:" + order.getOrderId());
}
}
static class Order implements Delayed{
private String orderId;
private long createTime;
private long delayTime;
public Order(String orderId, long createTime, long delayTime) {
this.orderId = orderId;
this.createTime = createTime;
this.delayTime = delayTime;
}
public String getOrderId() {
return orderId;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = createTime + delayTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
return Long.compare(diff, 0);
}
}
}
由于每个订单都有不同的延迟时间,因此它们将会按照延迟时间的顺序被取出。当延迟时间到达时, 对应的订单对象将会被从队列中取出,并被处理。