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

  • 相关阅读:
    grafan+cadvisor+prometheus监控docker
    容器化tomcat9.0
    Vue的四种特殊attribute:is key ref v-slot (更新中)
    properties 和 attributes的区别
    vue父子组件(更新中)
    发布者订阅者模式(vue双向绑定原理)
    开发中一些好的逻辑;
    vue项目根据不同环境调用不同请求地址(2)
    linux上删除文件名乱码的文件
    Oracle的SQL优化
  • 原文地址:https://www.cnblogs.com/billshen/p/13426107.html
Copyright © 2011-2022 走看看