zoukankan      html  css  js  c++  java
  • 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的实现原理简单来说就是单线程+最小堆+任务轮询

  • 相关阅读:
    git track
    npm 升级到最新版本
    三行代码实现垂直居中和cube
    布局之定位
    MongoDB的安装问题
    正则表达式
    javascript表单验证
    Oracle中创建表,行级触发器,序列
    查找某个字符在字符串中出现的次数
    oracle表中有一列id她是自动增长的,插入一条数据时怎么取得id的值
  • 原文地址:https://www.cnblogs.com/billshen/p/13426107.html
Copyright © 2011-2022 走看看