java延时队列 示例


/**
* @desc: java 延时队列 思路:使用java.util.concurrent.DelayQueue队列,
* 队列的元素需要实现Delayed接口的getDelay()和compareTo()两个方法
* @author: 毛会懂
* @create: 2022-02-08 17:20:00
**/
public class Test44Main {
public static void main(String[] args) throws IOException {

// 延迟队列
DelayQueue<Obj> queue = new DelayQueue<>();

// 线程1: 生产者 每隔2S产生一个对象
CompletableFuture.runAsync(()->{
System.out.println("启动生产者了");
for(int i = 5; i < 30;i+=5){
System.out.println("放入队列" + i);
Obj temp = new Obj(i,TimeUnit.SECONDS,"name_" + i);
queue.put(temp);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// 线程2: 消费者
CompletableFuture.runAsync(() ->{
System.out.println("启动消费者了");
while (true){
try {
Obj take = queue.take();
System.out.format("name={%s},time={%s},当前时间={%s} \n",take.name,take.time, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("主线程结束");
System.in.read();
}


/**
* @desc : 消费的对象需要实现Delayed接口的getDelay()和 compareTo()
* @author : 毛会懂
* @create: 2022/2/8 17:23:00
**/
public static class Obj implements Delayed {
private long time;
private String name;

public Obj(long time,TimeUnit unit,String name){
this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
this.name = name;
}

@Override
public long getDelay(TimeUnit unit) {
// return time;
return time - System.currentTimeMillis();
}

@Override
public int compareTo(Delayed o) {
Obj obj = (Obj)o;
long diff = this.time - obj.time ;
if(diff > 0){
return 1;
}else if (diff < 0){
return -1;
}
return 0;
}

@Override
public String toString() {
return "本对象的time=" + time + "name=" + name;
}
}

}
上一篇:Linux下利用Docker搭建MYSQL5.7


下一篇:Java类和对象