延迟队列DelayQueue

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeyincai/article/details/52774843

DelayQueue主要用于放置实现了Delay接口的对象,其中的对象只能在其时刻到期时才能从队列中取走。这种队列是有序的,即队头的延迟到期时间最短。如果没有任何延迟到期,那么久不会有任何头元素,并且poll()将返回null(正因为这样,你不能将null放置到这种队列中)

应用场景:消息延迟60秒发送,如果用调度去查询执行的话,会有误差

public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Message> delayQueue =  new DelayQueue<>();
        for (int i=1;i<11;i++){
            Message m = new Message(i+"",System.currentTimeMillis()+i*1000);
            delayQueue.add(m);
        }

        while(!delayQueue.isEmpty()){
            Message message = delayQueue.take();//此处会阻塞
            System.out.println(message.getId()+"消息发送:");
        }

    }
}

class Message  implements  Delayed{
    private String id;
    private long insertTime ;//开始时间

    public Message(String id,long insertTime){
        this.id = id;
        this.insertTime =  insertTime;
    }

    //获取失效时间
    @Override
    public long getDelay(TimeUnit unit) {
        //获取失效时间
        return this.insertTime+60000-System.currentTimeMillis();
    }


    @Override
    public int compareTo(Delayed o) {
        //比较 1是放入队尾  -1是放入队头
        Message that = (Message)o;
        if(this.insertTime>that.insertTime){
            return 1;
        }
        else  if(this.insertTime==that.insertTime){
            return 0;
        }else {
            return -1;
        }
    }

    public String getId() {
        return id;
    }
}

猜你喜欢

转载自blog.csdn.net/yeyincai/article/details/52774843