package com.example.demo;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;public class DeQueueTest { public static final Logger logger = LoggerFactory.getLogger(DeQueueTest.class); public static final int DELAY_PERIOD_SECONDS = 10; // 延时10秒 private final static DelayQueuedelayQueue = new DelayQueue (); /** * 以秒为单位计算耗时 */ static class DelayedElement implements Delayed { // 到期时间 public long expireTime; public String name; public DelayedElement(String name){ this.name = name; this.expireTime = (System.currentTimeMillis() / 1000) + DELAY_PERIOD_SECONDS; } @Override public int compareTo(Delayed o) { if(this.expireTime < ((DelayedElement)o).expireTime) return -1; else if(this.expireTime > ((DelayedElement)o).expireTime)return 1; else return 0; } public void reset() { this.expireTime = (System.currentTimeMillis() / 1000) + DELAY_PERIOD_SECONDS; } // 这边返回的值为0了,就表示到期了 @Override public long getDelay(TimeUnit unit) { long r = unit.convert(expireTime - (System.currentTimeMillis() / 1000), TimeUnit.SECONDS); return r; } public String getName() { return name; } } public static void main(String[] args) throws InterruptedException { delayQueue.offer(new DelayedElement("a1")); TimeUnit.SECONDS.sleep(3); delayQueue.offer(new DelayedElement("a2")); TimeUnit.SECONDS.sleep(1); delayQueue.offer(new DelayedElement("a3")); TimeUnit.SECONDS.sleep(2); delayQueue.offer(new DelayedElement("a4")); TimeUnit.SECONDS.sleep(3); delayQueue.offer(new DelayedElement("a5")); while(true) { DelayedElement element = delayQueue.poll(); if (element != null) { logger.warn(element.getName()); // 重新加入 element.reset(); delayQueue.offer(element); } Thread.sleep(100); } }}
按时间循环打印输出部分
09:58:18.033 [main] WARN com.example.demo.DeQueueTest - a109:58:21.098 [main] WARN com.example.demo.DeQueueTest - a209:58:22.082 [main] WARN com.example.demo.DeQueueTest - a309:58:24.042 [main] WARN com.example.demo.DeQueueTest - a409:58:27.086 [main] WARN com.example.demo.DeQueueTest - a509:58:28.062 [main] WARN com.example.demo.DeQueueTest - a109:58:31.024 [main] WARN com.example.demo.DeQueueTest - a209:58:32.005 [main] WARN com.example.demo.DeQueueTest - a309:58:34.089 [main] WARN com.example.demo.DeQueueTest - a4