JDK 自带定时器 Timer 核心原理代码

 主要逻辑: new 一个 Timer 后, timer  内部维护一个队列 queue,并开启一个死循环线程 从
queue 中取任务执行( 触发时间到了就执行,未到就 wait ),timer.schedule( TimerTask ) 其实就是 将 任务体放入队列中  ( ps: timer 运行多个 TimerTask 时只要一个没有捕获抛出的异常异常,则此 timer  便停止了,所以建议使用 ScheduledExecutorService 代替 Timer )


private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled){
                        // 任务队列中没有待调度的任务,just  wait!
                        queue.wait();
                    }
                    if (queue.isEmpty()){
                        break; // Queue is empty and will forever remain; die
                    }
                       
                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired){ // Task hasn't yet fired; wait
                        // 触发时间还没到, 延迟 wait
                        queue.wait(executionTime - currentTime);
                    }
                }
                if (taskFired){  // Task fired; run it, holding no locks
                    // 触发时间到了,执行任务体( 这里的 task  即是 实现了 Runnable 接口的 TimerTask 任务体 )
                    task.run();
                }
            } catch(InterruptedException e) {
            }
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值