BlockingQueue之DelayQueue的学习使用

DelayQueue 是一中阻塞队列,需要实现接口Delayed定义的方法.做下使用记录和心得吧,

 
  
@Data
public class DelayQueueExample implements Delayed {

private String beginTime;
private String name;

public static DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public LocalDateTime localDateTime;

public DelayQueueExample(String beginTime, String name) {
this.beginTime = beginTime ;
this.name = name;
}

@Override
public long getDelay(TimeUnit unit) {

// TimeUnit.NANOSECONDS.convert(1000,TimeUnit.DAYS);
//long ss= unit.convert(afterTime - System.nanoTime(), TimeUnit.MILLISECONDS);
// System.out.println("getDelay()"+ss);
//unit.convert(afterTime - System.nanoTime(), TimeUnit.MILLISECONDS)

//与当前时间对比,小于当前时间的话就进入队列,否则就抛弃这个队列的数据
localDateTime= LocalDateTime.parse(beginTime,dateTimeFormatter);
return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()- System.currentTimeMillis();//是否小于当前时间

}

@Override
public int compareTo(Delayed o) {
int temp = (int) (o.getDelay(TimeUnit.MILLISECONDS) - this.getDelay(TimeUnit.MILLISECONDS));
if (temp < 0) {
return 1;
}else {
return -1;
}
// return (int) (o.getDelay(TimeUnit.MILLISECONDS) - this.getDelay(TimeUnit.MILLISECONDS));
}

@Override
public String toString() {
return "DelayQueueExample{" +
"beginTime=" +(beginTime) +
", name='" + name + '\'' +
'}';
}


public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayQueueExample> delayQueue = new DelayQueue<DelayQueueExample>();
delayQueue.add(new DelayQueueExample("2018-06-18 00:45:00", "hhe100"));
delayQueue.add(new DelayQueueExample("2018-06-18 00:47:00", "hhe101"));
delayQueue.add(new DelayQueueExample("2018-06-08 00:46:00", "hhe102"));
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
DelayQueueExample element = null;
try {
element = delayQueue.poll();
if (element == null) {
break;
} else {
System.out.println(element);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();


}
}

源码部分:取值的逻辑相似

 public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            E first = q.peek();
            if (first == null || first.getDelay(NANOSECONDS) > 0)//丢掉延迟大于0的队列值
                return null;
            else
                return q.poll();
        } finally {
            lock.unlock();
        }
    }

超时加排序机制

 

 
 

 

转载于:https://www.cnblogs.com/jinjian91/p/9193325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值