【Java基础】DelayQueue

  1. 在J.U.C包中

  2. 是用PriorityQueue实现的

  3. 不允许null元素

  4. 使用ReentrantLock结合Condition,添加或移除元素要加锁。

  5. 类的定义:

    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);
        }
     }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值