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);
}
}
}
Task 类:
Delayed 接口,表示这是一个具有延迟特性的任务。name 是任务的名称。startTime 是任务开始执行的时间,等于当前时间加上延迟时间。getDelay 方法返回任务还需要等待的时间。compareTo 方法用于比较两个任务的延迟时间,确保任务按延迟时间排序。DelayQueueExample 类:
DelayQueue 对象,用于存储延迟任务。put 方法将任务添加到队列中,并设置不同的延迟时间。take 方法从队列中取出已经到期的任务并执行。take 方法会阻塞,直到有任务到期。通过这种方式,DelayQueue 可以管理一组需要在特定时间点执行的任务。
上一篇:java date减一天
下一篇:java isbefore
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站