DelayQueue理解
Posted yangfei629
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DelayQueue理解相关的知识,希望对你有一定的参考价值。
一、定义
时延队列,只要经过一段时间后才能从队列中取出。
特点:
1、无界的阻塞队列。
2、只能存放实现了Delayed接口的对象
时延就是通过getDelay获取的,getDelay<=0时,才能取出队列中的值
3、内部使用PriorityQueue , 比较的就是时延
二、使用
代码样例
public class DelayedBean implements Delayed { private long startTimeMills; private long delayMills; public DelayedBean(long startTimeMills, long delayMills) { this.startTimeMills = startTimeMills; this.delayMills = delayMills; } @Override public long getDelay(TimeUnit unit) { return unit.convert((startTimeMills+delayMills) - System.currentTimeMillis(),TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed object) { DelayedBean descObject = (DelayedBean) object; return (int)Long.compare(this.getDelay(TimeUnit.MILLISECONDS),descObject.getDelay(TimeUnit.MILLISECONDS)); } @Override public String toString() { return "DelayedBean{" + "startTimeMills=" + startTimeMills + ", delayMills=" + delayMills + ‘}‘; } public static void main(String[] args) throws InterruptedException { DelayQueue<DelayedBean> delayQueue = new DelayQueue<>(); delayQueue.offer(new DelayedBean(System.currentTimeMillis(),1000)); delayQueue.offer(new DelayedBean(System.currentTimeMillis(),2000)); Thread.sleep(1000); System.out.println("first get from delayqueue="+delayQueue.poll()); System.out.println("second get from delayqueue="+delayQueue.poll()); } }
输出:
first get from delayqueue=DelayedBean{startTimeMills=1591628168555, delayMills=1000}
second get from delayqueue=null
可见第一个元素达到了时延1000ms , 故可以取出
第二个元素为达到时延2000ms,故取不出返回null
以上是关于DelayQueue理解的主要内容,如果未能解决你的问题,请参考以下文章