-
在J.U.C包中
-
是用PriorityQueue实现的
-
不允许null元素
-
使用ReentrantLock结合Condition,添加或移除元素要加锁。
-
类的定义:
public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E>
也就是说,优先队列中的元素必须实现了Delayed接口。
Delayed接口如下:
public interface Delayed extends Comparable<Delayed> { /** * Returns the remaining delay associated with this object, in the * given time unit. * * @param unit the time unit * @return the remaining delay; zero or negative values indicate * that the delay has already elapsed */ long getDelay(TimeUnit unit); }
【例】实现了Delayed接口的一个类DelayedTimer,是TimerQueue的内部类。
TimerQueue和DelayedTimer的部分代码如下:class TimerQueue implements Runnable{ private final DelayQueue<DelayedTimer> queue; private final Lock runningLock; private static long now() { return System.nanoTime() - NANO_ORIGIN; } } static class DelayedTimer implements Delayed { /** The time the task is enabled to execute in nanoTime units */ //任务可以运行的时间,也就是存入的时间加延迟的时间 private volatile long time; //获取还需要延迟的时间getDelay,到期时间减去当前时间 final public long getDelay(TimeUnit unit) { return unit.convert(time - now(), TimeUnit.NANOSECONDS); } //重写Comparable的compareTo对两个DelayedTimer的到期时间进行对比 public int compareTo(Delayed other) { if (other == this) { // compare zero ONLY if same object return 0; } if (other instanceof DelayedTimer) { DelayedTimer x = (DelayedTimer)other; long diff = time - x.time; if (diff < 0) { return -1; } else if (diff > 0) { return 1; } else if (sequenceNumber < x.sequenceNumber) { return -1; } else { return 1; } } long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS)); return (d == 0) ? 0 : ((d < 0) ? -1 : 1); } }
【Java基础】DelayQueue
最新推荐文章于 2023-03-20 16:16:40 发布