DelayQueue使用实例

更新时间:2023-05-31 02:26:19 阅读: 评论:0

DelayQueue使⽤实例
DelayQueue是延迟阻塞队列。这种特性可以让我们做⼀些ArrayBlockingQueue、LinkedBlockingQueue这种常规阻塞队列所做不到的事情。⽐如说银⾏转账24h后才到账,微信转账2h到账或者24⼩时到账。
public class DelayQueueTest {
public static void main(String[] args) {
DelayQueue<MyTimerRunnable> blockingQueue = new DelayQueue<>();
blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 10 * 1000,
() -> System.out.println(10)));
blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 5 * 1000,
() -> System.out.println(5)));
blockingQueue.put(new MyTimerRunnable(System.currentTimeMillis() + 15 * 1000,
() -> System.out.println(15)));
System.out.println("开始---" + System.currentTimeMillis());
枸杞泡酒比例for (; ; ) {
try {
MyTimerRunnable timerRunnable = blockingQueue.take();
System.out.println("处理---" + System.currentTimeMillis());
Runnable runnable = Runnable();
if (runnable != null) {
runnable.run();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
张开来MyTimerRunnable是我们⾃定义的Delayed接⼝的实现类,⾥⾯定义了⼀些属性,包括执⾏时间以及执⾏的任务。⾃定义类必须实现Delayed接⼝的getDelay()⽅法和Delayed接⼝继承⾃Comoarable接⼝的compareTo()⽅法。
public class MyTimerRunnable implements Delayed {
private long processTime;
private Runnable runnable;
public long getProcessTime() {
return processTime;
}
public Runnable getRunnable() {
return runnable;
骊山烽火}
public MyTimerRunnable(long processTime, Runnable runnable) {
招商城
this.processTime = processTime;
this.runnable = runnable;
车间安全培训
}
@Override
public long getDelay(@NotNull TimeUnit unit) {
return processTime - System.currentTimeMillis();
}
@Override有梦不觉夜漫长
public int compareTo(@NotNull Delayed o) {
drain
return (int) (getProcessTime() - ((MyTimerRunnable) o).getProcessTime());
}
鲁滨逊漂流记有感}
打印结果是
开始---1584076398361
处理---1584076403361
5
处理---1584076408322
10
处理---1584076413361
15

本文发布于:2023-05-31 02:26:19,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/817346.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:阻塞   队列   定义   包括
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图