DelayQueue使⽤实例
DelayQueue是延迟阻塞队列。这种特性可以让我们做⼀些ArrayBlockingQueue、LinkedBlockingQueue这种常规阻塞队列所做不到的事情。⽐如说银⾏转账24h后才到账,微信转账2h到账或者24⼩时到账。
bells of freedompublic class DelayQueueTest {
public static void main(String[] args) {
norwayDelayQueue<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)));
need
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) {
soee.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) {
return (int) (getProcessTime() - ((MyTimerRunnable) o).getProcessTime());
}
}
打印结果是
开始---1584076398361
处理---1584076403361
5
处理---1584076408322
10
处理---1584076413361
15
miles