企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ### `LinkedBlockingQueue` * `FixedThreadPool`和`SingleThreadExecutor`中的阻塞队列 <br/> > ### `SynchronousQueue` * `CachedThreadPool`中的阻塞队列 <br/> > ### `DelayQueue` * `ScheduledThreadPoolExecutor`中的阻塞队列 * 使用实例,元素需要继承`Delayed`接口 ``` public class DelayQueueTest { static class Element implements Delayed{ long expireTime; String msg; public Element(long expireTime, String msg){ this.expireTime = expireTime; this.msg = msg; } @Override public long getDelay(TimeUnit unit) { return unit.convert(this.expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return (int) (this.getDelay(TimeUnit.MILLISECONDS) -o.getDelay(TimeUnit.MILLISECONDS)); } } public static void main(String[] args) { DelayQueue delayQueue = new DelayQueue(); long now = System.currentTimeMillis(); delayQueue.add(new Element(now + 1000, "1")); delayQueue.add(new Element(now + 2000, "2")); delayQueue.add(new Element(now + 3000, "3")); while(!delayQueue.isEmpty()){ try{ Element e = (Element) delayQueue.take(); System.out.println(e.msg); }catch(InterruptedException e){ e.printStackTrace(); } } } } ```