当前位置:网站首页>DelayQueue延迟队列的使用和场景
DelayQueue延迟队列的使用和场景
2022-07-05 07:11:00 【泡^泡】
一个实现PriorityBlockingQueue实现延迟获取的无界队列,在创建元素时,可以指定多久才能从队列中获取当前元素。只有延时期满后才能从队列中获取元素。
使用场景:
1.定时任务调度。使用DelayQueue保存当天将会执行的任务和执行时间,一旦从DelayQueue中获取到任务就开始执行,从比如TimerQueue就是使用DelayQueue实现的。
2.缓存系统的设计:可以用DelayQueue保存缓存元素的有效期,使用一个线程循环查询DelayQueue,一旦能从DelayQueue中获取元素时,表示缓存有效期到了。
3.订单延迟支付关闭。(MQ延迟消息队列/时间轮/定时任务)
代码案例
package thread;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class DelayQueueExampleTask implements Delayed {
private String orderId;
private long start = System.currentTimeMillis();
private long time;
public DelayQueueExampleTask(String orderId,long time) {
this.orderId = orderId;
this.time = time;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert((start+time)-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return (int)(this.getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS));
}
@Override
public String toString() {
return "DelayQueueExampleTask{" +
"orderId='" + orderId + '\'' +
", start=" + start +
", time=" + time +
'}';
}
}
package thread;
import java.util.concurrent.DelayQueue;
public class DelayQueueExampleTaskTest {
private static DelayQueue<DelayQueueExampleTask> delayQueue = new DelayQueue();
public static void main(String[] args) {
delayQueue.offer(new DelayQueueExampleTask("1001",1000));
delayQueue.offer(new DelayQueueExampleTask("1002",2000));
delayQueue.offer(new DelayQueueExampleTask("1003",3000));
delayQueue.offer(new DelayQueueExampleTask("1004",5000));
delayQueue.offer(new DelayQueueExampleTask("1005",6000));
delayQueue.offer(new DelayQueueExampleTask("1006",7000));
delayQueue.offer(new DelayQueueExampleTask("1007",8000));
delayQueue.offer(new DelayQueueExampleTask("1008",3000));
while(true){
try {
DelayQueueExampleTask task = delayQueue.take();
System.out.println(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
执行效果:
边栏推荐
- 能量守恒和打造能量缺口
- Logical structure and physical structure
- Ros2 - first acquaintance with ros2 (I)
- Lexin interview process
- MySQL setting trigger problem
- Intelligent target detection 59 -- detailed explanation of pytoch focal loss and its implementation in yolov4
- 全局变量和静态变量的初始化
- SD_CMD_SEND_SHIFT_REGISTER
- Orin installs CUDA environment
- UIO driven framework
猜你喜欢
随机推荐
Marvell 88E1515 PHY loopback模式测试
Concurrent programming - deadlock troubleshooting and handling
Build a microservice cluster environment locally and learn to deploy automatically
In C language, int a= 'R'
ROS2——常用命令行(四)
MySQL setting trigger problem
全局变量和静态变量的初始化
ROS2——Service服务(九)
Unity UGUI不同的UI面板或者UI之间如何进行坐标匹配和变换
The difference between NPM install -g/-save/-save-dev
Orin 两种刷机方式
ROS2——node节点(七)
【无标题】
ROS2——ROS2对比ROS1(二)
Technical conference arrangement
Ros2 - workspace (V)
摄像头的MIPI接口、DVP接口和CSI接口
[software testing] 04 -- software testing and software development
Technology blog learning website
数学分析_笔记_第8章:重积分