模擬五秒鐘後獲取信息ide
public class DelayQueueDemo { static class DelayedVo implements Delayed {//必須實現Delayed接口 private long activeTime; private String name; public DelayedVo(String name, long activeTime) { this.name = name; this.activeTime = TimeUnit.NANOSECONDS.convert(activeTime, TimeUnit.MILLISECONDS) + System.nanoTime();//存活時間加當前時間 } @Override public long getDelay(TimeUnit unit) { return unit.convert(activeTime - System.nanoTime(), TimeUnit.NANOSECONDS);//剩餘時間 } @Override public int compareTo(Delayed o) { long t = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS); return t == 0 ? 0 : (t > 0 ? 1 : -1); } public String getName() { return name; } } static class ReadThread implements Runnable { private DelayQueue<DelayedVo> queue; public ReadThread(DelayQueue<DelayedVo> queue) { this.queue = queue; } @Override public void run() { try { DelayedVo delayedVo = queue.take(); System.out.println(delayedVo.getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } static class WriteThread implements Runnable { private DelayQueue<DelayedVo> queue; public WriteThread(DelayQueue<DelayedVo> queue) { this.queue = queue; } @Override public void run() { DelayedVo delayedVo = new DelayedVo("abc", 5000); queue.put(delayedVo); } } public static void main(String[] args) { DelayQueue<DelayedVo> queue =new DelayQueue<> (); new Thread(new WriteThread(queue)).start(); new Thread(new ReadThread(queue)).start(); } }