延时队列主要应用场景是用户登录后延时推送消息,通知等,一般用mq中间件来弄,下面我来用java实现 一、消息实体类实现Delayed接口
import lombok.Data;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* 消息实体类实现Delayed接口
* @author zhanqi
* @since 2021/5/13 13:46
*/
@Data
public class Message implements Delayed {
private String body;
private Long executeTime;
public Message(String body,Long executeTime, TimeUnit unit){
this.body=body;
this.executeTime= System.currentTimeMillis() + (executeTime > 0? unit.toMillis(executeTime): 0);
}
@Override
public long getDelay(TimeUnit unit) {
return executeTime - System.currentTimeMillis();
}
@Override
public int compareTo(Delayed o) {
Message msg = (Message) o;
long diff = this.executeTime - msg.executeTime;
//diff>0是一次取出
if (diff <= 0) {
return -1;
} else {
return 1;
}
}
}
二、main运行,这里用System.in模拟添加数据
import java.util.Scanner;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
/**
* @author zhanqi
* @since 2021/5/13 13:47
*/
public class DelayQueueTest {
public static void main(String[] args) {
// 创建延时队列
DelayQueue<Message> queue = new DelayQueue<>();
new Thread(new Consumer(queue)).start();
Scanner input = new Scanner(System.in);
//循环添加System.in
while (true) {
String str = input.next();
if (null != str) {
Message m = new Message(str, 5l, TimeUnit.SECONDS);
queue.offer(m);
}
}
}
}
三、运行结果,延时效果已经出现
四、我们现在测试延时批量取出修改代码将diff<=0改diff>0
五、效果是一次取出