标签:bsp ret 输出 mil cep rri str code 阻塞队列
一、定义
时延队列,只要经过一段时间后才能从队列中取出。
特点:
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
标签:bsp ret 输出 mil cep rri str code 阻塞队列
原文地址:https://www.cnblogs.com/yangfei629/p/13069223.html