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 diff = startTime - System.currentTimeMillis();
        return unit.convert(diff, 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("Task1", 2000)); // 2秒后执行
        queue.put(new Task("Task2", 1000)); // 1秒后执行
        queue.put(new Task("Task3", 5000)); // 5秒后执行
        while (!queue.isEmpty()) {
            // 获取并移除队列头部的元素,只有当其延迟期已到时才会这样做。
            Task task = queue.take();
            System.out.println("Executing: " + task);
        }
    }
}DelayQueue 是一个无界阻塞队列,它只会在元素的延迟到期之后才能从中获取该元素。Task 类实现了 Delayed 接口,表示一个具有延迟特性的任务。每个任务都有一个名称和一个开始时间(相对于当前时间的延迟)。getDelay 方法返回任务剩余的延迟时间。compareTo 方法用于比较两个任务的延迟时间,确保队列中的任务按延迟时间排序。main 方法中,我们创建了一个 DelayQueue 并添加了几个任务,每个任务有不同的延迟时间。然后通过 take() 方法依次取出并执行到期的任务。上一篇:calendar java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站