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(); } }
超时加排序机制