Delayed ,DelayedQueue的使用

因为并发看到了ScheduledThreadPoolExecutor的实现里面有Dealyed,所以就学习一下基本使用,网上资料也不少,

Delayed这个接口继承了Comparable这个接口,所以实现这个接口现需要实现getDelay()和comapreTo方法;

对于getDelay方法里面的参数我一开始比较疑惑。因为看到的别人博客的示例代码有的没用到这个参数,所以不知道这个参数是干啥的。只知道要统一时间单位。在ScheduledThreadPoolExecutor的实现中找到了它的一种实现和使用。我们在实现中最好也按照jdk源码中的实现这样来写。

在DelayedQueue中也找到了里面的使用。

所以可以知道,在包装中,最后是转化为纳秒(TimeUnit.NANOSECONDS),也很好理解,因为这是里面最小的时间刻度了 ,也就是最精确。

在个人使用中,推荐使用ScheduledThreadPoolExecutor 中getDelay( )的实现。

下面是对DelayQueue的测试。

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedQueneTest {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Item> delayQueue = new DelayQueue<>();
        delayQueue.add(new Item(10,"item1"));
        delayQueue.add(new Item(15,"item2"));
        delayQueue.add(new Item(5,"item3"));
        delayQueue.add(new Item(20,"item4"));
        int size = delayQueue.size();
        for(int i=0;i< size;i++){
            System.out.println(delayQueue.take().toString());
        }
    }
    static class Item implements Delayed{
        private long time;
        private long delayTime;
        private String Name;
        public Item(long time,String name){
            this.delayTime = time;
            //因为是纳秒时间,所以如果直接time+system.nanoTime体现不出time的影响,所以提高
            // time的权重
            this.time = time*1000000 + System.nanoTime();
            this.Name = name;
        }

        @Override
        public String toString() {
            return Name+" "+this.delayTime;
        }

        @Override
        public long getDelay(TimeUnit timeUnit) {
            return timeUnit.convert(this.time - System.nanoTime(),TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed delayed) {
            return this.time - ((Item)delayed).time > 0 ? 1 : -1;
        }
    }
}

输出如下 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值