示例

模拟五秒钟后获取信息

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();
    }
}

大军
847 声望183 粉丝

学而不思则罔,思而不学则殆