Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java delayqueue

作者:颠沛流离的伤   发布日期:2025-08-25   浏览:41

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

class Task implements Delayed {
    private final String name;
    private final long startTime;

    public Task(String name, long delayInMilliseconds) {
        this.name = name;
        this.startTime = System.currentTimeMillis() + delayInMilliseconds;
    }

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

    @Override
    public int compareTo(Delayed o) {
        if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
            return -1;
        }
        if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
            return 1;
        }
        return 0;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Task> queue = new DelayQueue<>();

        // 添加任务到队列中,设置延迟时间
        queue.put(new Task("Task 1", 2000));
        queue.put(new Task("Task 2", 5000));
        queue.put(new Task("Task 3", 3000));

        while (!queue.isEmpty()) {
            // 取出已经到期的任务
            Task task = queue.take();
            System.out.println("Executing: " + task);
        }
    }
}

解释说明

  1. Task:

    • 实现了 Delayed 接口,表示这是一个具有延迟特性的任务。
    • name 是任务的名称。
    • startTime 是任务开始执行的时间,等于当前时间加上延迟时间。
    • getDelay 方法返回任务还需要等待的时间。
    • compareTo 方法用于比较两个任务的延迟时间,确保任务按延迟时间排序。
  2. DelayQueueExample:

    • 创建了一个 DelayQueue 对象,用于存储延迟任务。
    • 使用 put 方法将任务添加到队列中,并设置不同的延迟时间。
    • 使用 take 方法从队列中取出已经到期的任务并执行。take 方法会阻塞,直到有任务到期。

通过这种方式,DelayQueue 可以管理一组需要在特定时间点执行的任务。

上一篇:java date减一天

下一篇:java isbefore

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站