java 自定义延迟队列

167 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

/**
 * 自定义延迟队列
 * @author 
 * @date 2020/4/12 19:07
 */
public class CustomDelayQueue {
    // 延迟消息队列
    private static DelayQueue delayQueue = new DelayQueue();

    // 生产者
    public static void producer() {
        // 添加消息
        delayQueue.put(new Delay(2000,"1"));
        delayQueue.put(new Delay(10000,"1"));
    }
   // 消费者
    public static void consumer() throws Exception {
       System.out.println("开始执行时间:"+ DateFormat.getDateTimeInstance().format(new Date()));
       while (!delayQueue.isEmpty()) {
           System.out.println(delayQueue.take());
       }
        System.out.println("结束执行时间:"+ DateFormat.getDateTimeInstance().format(new Date()));

    }

    static class Delay implements Delayed {

        long delayTime =   System.currentTimeMillis();

        private String msg ;


        public Delay (long delayTime,String msg) {
            this.delayTime =(this.delayTime+ delayTime);
            this.msg =msg;
        }

         public String getMsg() {
             return msg;
         }

         public void setMsg(String msg) {
             this.msg = msg;
         }

         // 获取剩余时间
         @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(delayTime -System.currentTimeMillis(),TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
                return  1;
            } else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
                return  -1;
            } else {
                return 0;
            }
        }

         @Override
         public String toString() {
             return "Delay{" +
                     "delayTime=" + delayTime +
                     ", msg='" + msg + ''' +
                     '}';
         }
     }

    public static void main(String[] args) throws Exception {
       // 生产者
        producer();
        //消费者
        consumer();
    }
}