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 = timerRunnable.getRunnable(); 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) { return (int) (getProcessTime() - ((MyTimerRunnable) o).getProcessTime()); } }
打印结果是
开始---1584076398361
处理---1584076403361
5
处理---1584076408322
10
处理---1584076413361
15