延迟队列DelayQueue

1.什么是延时队列

delayed元素的无限制阻塞队列,在该队列中,仅当元素的延迟到期时才可以使用该元素。
队列的开头是该Delayed元素,其延迟在过去最远的时间到期。 如果没有延迟,则没有头, poll将返回null 。
当元素getDelay(TimeUnit.NANOSECONDS)方法返回小于或等于零的值时,就会发生过期。
即使未到期的元素无法使用take或poll删除,它们也被视为普通元素。 例如, size方法返回过期和未过期元素的计数。
此队列不允许使用null元素。 此类及其迭代器实现Collection和Iterator接口的所有可选方法。
不保证方法iterator()提供的Iterator以任何特定顺序遍历DelayQueue的元素。(官方注释翻译)

2.使用场景

定时任务,需要定时触发的就可以使用延时队列,把需要触发的任务放到延时队列中。
1.订单超时,下单超过15分钟不付款自动取消订单。
2.清除内存中缓存的对象,如果超过时间就清除。
3. 关闭空闲连接。服务器中,有很多客户端的连接,空闲一段时间之后需要关闭之。
4. 任务超时处理。在网络协议滑动窗口请求应答式交互时,处理超时未响应的请求等。

3.上代码

创建一个Task类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Task implements Delayed {

    private int taskId;

    private String taskName;

    private long scheduleAt;

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.scheduleAt - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        Task task = (Task) o;
        return Long.compare(this.scheduleAt, task.scheduleAt);
    }
}

简单的调度系统

public class Schedule extends Thread {

    public static final DelayQueue<Task> DELAY_QUEUE = new DelayQueue<>();

    @Override
    public void run() {
        while (true) {
            try {
                Task task = DELAY_QUEUE.take();
                System.out.println("Current time" + System.currentTimeMillis() + " trigger task: " + task);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        //用于创建任务
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Task task = new Task(i, "task" + i, System.currentTimeMillis());
                System.out.println("Create task: " + task);
                DELAY_QUEUE.offer(task);
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //定时任务的线程
        Schedule schedule = new Schedule();
        schedule.start();
        //阻塞
        System.out.println(System.in);
    }
}

4.执行结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
延迟队列DelayQueue)是 Java 并发包中提供的一种队列实现,用于存储具有延迟时间的元素。延迟队列中的元素只有在其指定的延迟时间过去后才能被取出。 下面是一个简单的延迟队列的 Java 实现示例: 首先,我们需要定义一个实现了 Delayed 接口的延迟元素类: ```java import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayedElement implements Delayed { private String data; private long startTime; public DelayedElement(String data, long delay) { this.data = data; this.startTime = System.currentTimeMillis() + delay; } @Override public long getDelay(TimeUnit unit) { long diff = startTime - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed other) { if (this.startTime < ((DelayedElement) other).startTime) { return -1; } if (this.startTime > ((DelayedElement) other).startTime) { return 1; } return 0; } // Getter and Setter methods } ``` 然后,我们可以使用 DelayQueue 来存储延迟元素,并在需要时取出元素: ```java import java.util.concurrent.DelayQueue; public class DelayQueueExample { public static void main(String[] args) throws InterruptedException { DelayQueue<DelayedElement> delayQueue = new DelayQueue<>(); // 添加延迟元素到队列 delayQueue.add(new DelayedElement("Element 1", 2000)); // 延迟 2 秒 delayQueue.add(new DelayedElement("Element 2", 5000)); // 延迟 5 秒 delayQueue.add(new DelayedElement("Element 3", 1000)); // 延迟 1 秒 // 取出延迟元素并处理 while (!delayQueue.isEmpty()) { DelayedElement element = delayQueue.take(); System.out.println("Processing element: " + element.getData()); } } } ``` 在上面的示例中,我们创建了一个 DelayQueue 对象,并向其中添加了三个延迟元素。然后,我们使用 `take()` 方法从队列中取出元素,并进行处理。如果队列为空,`take()` 方法会阻塞等待,直到有延迟元素可用。 请注意,延迟时间的单位可以根据需要进行调整,例如使用 `TimeUnit.SECONDS` 表示秒。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值