延迟队列DelayQueue
应用场景:有一批广告需要不定时上下架,有可能上下架的时间间隔很长,就没必要用定时器轮询,用延迟队列进行任务执行。
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();//此处会阻塞
//执行广告上下架操作
}
}
}
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;
}
}

浙公网安备 33010602011771号