java并发编程学习之DelayQueue

示例

模拟五秒钟后获取信息

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 queue;

        public ReadThread(DelayQueue 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 queue;

        public WriteThread(DelayQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            DelayedVo delayedVo = new DelayedVo("abc", 5000);
            queue.put(delayedVo);
        }
    }

    public static void main(String[] args) {
        DelayQueue queue =new DelayQueue<> ();
        new Thread(new WriteThread(queue)).start();
        new Thread(new ReadThread(queue)).start();
    }
}

你可能感兴趣的:(java)