当前位置:网站首页>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();
}
}
}
}
执行效果:
边栏推荐
猜你喜欢
随机推荐
Negative number storage and type conversion in programs
The differences and connections among cookies, sessions, JWT, and tokens
Xavier CPU & GPU 高负载功耗测试
Ret2xx---- common CTF template proposition in PWN
PostMessage communication
In C language, int a= 'R'
MySQL setting trigger problem
Sre core system understanding
[untitled]
ROS2——安装ROS2(三)
Three body goal management notes
【软件测试】03 -- 软件测试概述
PHY drive commissioning - phy controller drive (II)
An article was opened to test the real situation of outsourcing companies
[software testing] 03 -- overview of software testing
SRE核心体系了解
cgroup_ memcg
ImportError: No module named ‘Tkinter‘
逻辑结构与物理结构
Energy conservation and creating energy gap