DelayQueue
是一种特殊的阻塞队列,只有到期的对象,才能从队列中取出。
底层有用到 PriorityQueue
,入队时会进行排序。也就是说,这个阻塞队列是有序的。
典型的应用场景,比如:12306订票,30分钟内未支付,则取消订单。
实现这样的功能,用定时任务是刷,当然可以。但用DelayQueue
会更精确。
一、示例代码
public static void main(String[] args) throws Exception {
long base = System.currentTimeMillis();
DelayQueue<Food> queue = new DelayQueue<>();
for(int i = 0; i < 10; i++){
String name = "food_" + i;
int cookedMinutes = RandomUtil.randomInt(1,20);
Food food = new Food(name, cookedMinutes);
log.info("name:{}, cookeMinutes:{}",name, cookedMinutes);
queue.offer(food);
}
log.info("all foods OK");
for(int i = 0; i < 10; i++){
Food food = queue.take();
log.info("foodName:{}, time:{}",food.name,(food.cookedSeconds - base) / 1000 );