当前位置:网站首页>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();
}
}
}
}
执行效果:
边栏推荐
猜你喜欢
随机推荐
在本地搭建一个微服务集群环境,学习自动化部署
【软件测试】05 -- 软件测试的原则
Qt项目中的日志库log4qt使用
cgroup_ memcg
Docker installs MySQL and uses Navicat to connect
1290_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
解读最早的草图-图像翻译工作SketchyGAN
一文揭开,测试外包公司的真实情况
【obs】x264编码:“buffer_size“
2022.06.27_每日一题
Matlab在线性代数中的应用(四):相似矩阵及二次型
kata container
*P++, (*p) + +, * (p++) differences
SD_ CMD_ SEND_ SHIFT_ REGISTER
iNFTnews | 喝茶送虚拟股票?浅析奈雪的茶“发币”
mingling
ROS2——工作空间(五)
testing framework
Xavier CPU & GPU 高负载功耗测试
Netease to B, soft outside, hard in








