【Java实现定时器】

class Task implements Comparable<Task>{
    //任务具体要干啥
    private Runnable runnable;
    //任务具体啥时候干,保存任务要执行的毫秒级时间戳
    private long time;

    //after是一个时间间隔,不是绝对的时间戳的值
    public Task(Runnable runnable, long after) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + after;
    }

    public void run(){
        runnable.run();
    }

    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(Task o) {
        return (int) (this.time - o.time);
    }
}

class Timer{
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long time){
        Task task = new Task(runnable,time);
        queue.put(task);
        //每次任务插入成功之后,都唤醒一下扫描线程,让线程重新扫描一下队首的任务时间到了是否执行
        synchronized (locker){
            locker.notify();
        }

    }

    private Object locker = new Object();

    public Timer(){
        Thread t = new Thread(() ->{
            while (true){
                try {
                    //先取出队首元素
                    Task task = queue.take();
                    //再比较一下看看这个任务时间到了没
                    long curTime = System.currentTimeMillis();
                    if (curTime < task.getTime()){
                        //时间没到,把任务再放回到队列当中
                        queue.put(task);
                        //指定等待时间
                        synchronized (locker){
                            locker.wait(task.getTime() - curTime);
                        }
                    }else {
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Day0813_1 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        },3000);
        System.out.println("hello main");
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值