图解DelayQueue源码(java 8)——延时队列的小九九

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 );
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值