/** * 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; } } } }