Timer实现原理

使用方法

Timer是一个定时任务触发装置,设置任务,触发延时和触发间隔就可以定时执行任务。以下是个简单的输出任务,每隔1000ms执行一次。

public class TimerLearn {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("timerTask");
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }
}

内部原理

Timer内部有个TimerThread线程,初始化的时候会开启。TaskQueue队列保存着任务,TaskQueue按执行时间进行堆排序。

public class Timer {
    private final TaskQueue queue = new TaskQueue();
    private final TimerThread thread = new TimerThread(queue);
    public Timer() {
        this("Timer-" + serialNumber());
    }
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }
}

TimerThread内部的队列就是Timer里面队列的引用,mainLoop是个死循环,不断从queue里取最近的一个需要执行的。

public class TimerThread extends Thread {
    private TaskQueue queue;
    public void run() {
        try {
            mainLoop();//执行死循环
        } finally {
            // Someone killed this Thread, behave as if Timer cancelled
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }
    private void mainLoop() {
        while (true) {
       task = queue.getMin(); 
//循环从queue里取任务执行,如果没有任务就进入阻塞 } } }

 总结

Timer的实现原理简单来说就是单线程+最小堆+任务轮询

原文地址:https://www.cnblogs.com/billshen/p/13426107.html