Java8的几个实用新特性

延迟队列 【Delay Queue】

它是一种特定类型的 Java 集合,它允许我们根据元素的延迟时间对元素进行排序。老实说,这是一门非常有趣的课。尽管 DelayQueue该类是 Java 集合的成员,但它属于 java.util.concurrent 包。它实现了BlockingQueue接口。只有当元素的时间到期时,才能从队列中取出元素

1
2
3
4
5
6
7
8
9
10
11
12
public record DelayedEvent(long startTime, String msg) implements Delayed {

public long getDelay(TimeUnit unit) {
long diff = startTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}

public int compareTo(Delayed o) {
return (int) (this.startTime - ((DelayedEvent) o).startTime);
}

}

假设我们想推迟元素10秒。我们只需要设置当前时间增加了10秒DelayedEvent类

1
2
3
4
5
final DelayQueue<DelayedEvent> delayQueue = new DelayQueue<>();
final long timeFirst = System.currentTimeMillis() + 10000;
delayQueue.offer(new DelayedEvent(timeFirst, "1"));
log.info("Done");
log.info(delayQueue.take().msg());