首页 > 其他 > 详细

DelayQueue

时间:2019-12-16 21:31:36      阅读:82      评论:0      收藏:0      [点我收藏+]
/**
 *    DelayQueue 底层包含一个PriorityQueue。
 *    向DelayQueue插入的元素必须实现delay接口,DelayQueue是不边界的
 *   只有当队列中的元素过期了,即getDalay方法返回值小于0,元素才可以取出来
 *   当元素过期了不取出来,不会被删除,元素仍然在队列里
 */
public class DelayQueueTest {


    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Element<String>> queue = new DelayQueue<Element<String>>();
        queue.put(new Element<>("hello1", 3000));
        long start = System.currentTimeMillis();
        System.out.println("=========");
        // TimeUnit.SECONDS.sleep(5);  //验证元素过期了不取出来,不会被删除
        queue.take();
        System.out.println(System.currentTimeMillis()-start);
    }



    static  class  Element<E>   implements Delayed{

        final  E e;

        long expireTime;
        Element (E e , long  expireTime){
            this.e = e;
            this.expireTime = System.currentTimeMillis() + expireTime;
        }


        @Override
        public long getDelay(TimeUnit unit) {
            return expireTime - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed o) {
            Element that = (Element) o;
            if(this.expireTime < that.expireTime){
                return  -1;
            }else if(this.expireTime > that.expireTime){
                return  1;
            }else{
                return 0;
            }
        }
    }
}

DelayQueue

原文:https://www.cnblogs.com/moris5013/p/12051330.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!