Timer

public class Timer1 {

    private final TaskQueue queue = new TaskQueue();//这是一个最小堆,它存放所有TimerTask。一个数组

    //定时任务只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间
    private final TimerThread thread = new TimerThread(queue);//queue中的任务,执行完从任务队列中移除。

    /**
     * This object causes the timer's task execution thread to exit
     * gracefully when there are no live references to the Timer object and no
     * tasks in the timer queue.  It is used in preference to a finalizer on
     * Timer as such a finalizer would be susceptible to a subclass's
     * finalizer forgetting to call it.

     */
    private final Object threadReaper = new Object() {
        protected void finalize() throws Throwable {
            synchronized(queue) {
                thread.newTasksMayBeScheduled = false;
                queue.notify(); // In case queue is empty.
            }
        }
    };

    private final static AtomicInteger nextSerialNumber = new AtomicInteger(0);
    private static int serialNumber() {
        return nextSerialNumber.getAndIncrement();
    }

    public Timer1() {
        this("Timer-" + serialNumber());
    }

    public Timer1(boolean isDaemon) {
        this("Timer-" + serialNumber(), isDaemon);//是否守护线程
    }

    public Timer1(String name) {
        thread.setName(name);
        thread.start();
    }

    public Timer1(String name, boolean isDaemon) {
        thread.setName(name);
        thread.setDaemon(isDaemon);
        thread.start();
    }

    public void schedule(TimerTask1 task, long delay) {//在时间等于或超过time的时候执行且只执行一次task,
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        sched(task, System.currentTimeMillis()+delay, 0);
    }

    public void schedule(TimerTask1 task, Date time) {
        sched(task, time.getTime(), 0);
    }

    public void schedule(TimerTask1 task, long delay, long period) {//在时间等于或超过time的时候首次执行task,之后每隔period毫秒重复执行一次task 。
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        if (period 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, System.currentTimeMillis()+delay, -period);
    }

    public void schedule(TimerTask1 task, Date firstTime, long period) {
        if (period 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, firstTime.getTime(), -period);
    }

    public void scheduleAtFixedRate(TimerTask1 task, long delay, long period) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        if (period 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, System.currentTimeMillis()+delay, period);
    }

    public void scheduleAtFixedRate(TimerTask1 task, Date firstTime,
                                    long period) {
        if (period 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, firstTime.getTime(), period);
    }

    private void sched(TimerTask1 task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");
        // Constrain value of period sufficiently to prevent numeric
        // overflow while still being effectively infinitely large.
        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");
            synchronized(task.lock) {
                if (task.state != TimerTask1.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask1.SCHEDULED;
            }
            queue.add(task);
            //当timer对象调用schedule方法时,都会向队列添加元素,并唤醒TaskQueue队列上的线程,
            //这时候TimerThread会被唤醒,继续执行mainLoop方法。
            if (queue.getMin() == task)
                queue.notify();//多线程对同一队列出队入队,使用synchronized,queue.notify()
        }
    }

    public void cancel() {
        synchronized(queue) {
            thread.newTasksMayBeScheduled = false;
            queue.clear();
            queue.notify();  // In case queue was already empty.
        }
    }

     public int purge() {
         int result = 0;
         synchronized(queue) {
             for (int i = queue.size(); i > 0; i--) {
                 if (queue.get(i).state == TimerTask1.CANCELLED) {
                     queue.quickRemove(i);
                     result++;
                 }
             }
             if (result != 0)
                 queue.heapify();
         }
         return result;
     }
}

class TimerThread extends Thread {
    /**
     * This flag is set to false by the reaper to inform us that there
     * are no more live references to our Timer object.  Once this flag
     * is true and there are no more tasks in our queue, there is no
     * work left for us to do, so we terminate gracefully.  Note that
     * this field is protected by queue's monitor!

     */
    boolean newTasksMayBeScheduled = true;

    private TaskQueue queue;

    TimerThread(TaskQueue queue) {
        this.queue = 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) {//函数执行的是一个死循环
            try {
                TimerTask1 task;
                boolean taskFired;
                synchronized(queue) {//并且加了queue锁,从而保证是线程安全的。
                    // 队列为空等待
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        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();
                    /*
                    queue.getMin()找到任务队列中执行时间最早的元素,
                      然后判断元素的state,period,nextExecutionTime,SCHEDULED等属性,从而确定任务是否可执行。
                       主要是判断这几个属性:1,state 属性,如果为取消(即我们调用了timer的cancel方法取消了某一任务),
                       则会从队列中删除这个元素,然后继续循环;2,period 属性,如果为单次执行,这个值为0,周期执行的话,
                       为我们传入的intervalTime值,如果为0,则会移出队列,并设置任务状态为已执行,然后下面的 task.run()会执行任务,
                       如果这个值不为0,则会修正队列,设置这个任务的再一次执行时间,queue.rescheduleMin这个函数来完成的这个操作; 3,taskFired
                       属性, 如果 executionTime*/
                    synchronized(task.lock) {
                        if (task.state == TimerTask1.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTimecurrentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask1.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    //会对TaskQueue队列的首元素进行判断,看是否达到执行时间,
                    //如果没有,则进行休眠,休眠时间为队首任务的开始执行时间到当前时间的时间差。
                    if (!taskFired)
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)
                    task.run();
            } catch(InterruptedException e) {
            }
        }
    }
}

class TaskQueue {

    /*TaskQueue是一个平衡二叉堆,具有最小 nextExecutionTime 的 TimerTask 在队列中为 queue[1] ,
                  也就是堆中的根节点。第 n 个位置 queue[n] 的子节点分别在 queue[2n] 和 queue[2n+1]

                  也就是说TimerTask 在堆中的位置其实是通过nextExecutionTime 来决定的。
      nextExecutionTime 越小,那么在堆中的位置越靠近根,越有可能先被执行。而nextExecutionTime意思就是下一次执行开始的时间。
    */
    private TimerTask1[] queue = new TimerTask1[128];//默认128

    private int size = 0;

    int size() {
        return size;
    }

    void add(TimerTask1 task) {//根据执行时间的先后对数组元素进行排序,从而确定最先开始执行的任务,
        if (size + 1 == queue.length)
            queue = Arrays.copyOf(queue, 2*queue.length);
        queue[++size] = task;
        fixUp(size);
    }

    TimerTask1 getMin() {
        return queue[1];
    }

    TimerTask1 get(int i) {
        return queue[i];
    }

    void removeMin() {
        queue[1] = queue[size];
        queue[size--] = null;  // Drop extra reference to prevent memory leak
        fixDown(1);
    }

    /**
     * Removes the ith element from queue without regard for maintaining
     * the heap invariant.  Recall that queue is one-based, so
     * 1 */
    void quickRemove(int i) {
        assert i  size;
        queue[i] = queue[size];
        queue[size--] = null;  // Drop extra ref to prevent memory leak
    }

    /**
     * Sets the nextExecutionTime associated with the head task to the
     * specified value, and adjusts priority queue accordingly.

     */
    void rescheduleMin(long newTime) {
        queue[1].nextExecutionTime = newTime;
        fixDown(1);
    }

    boolean isEmpty() {
        return size==0;
    }

    void clear() {
        // Null out task references to prevent memory leak
        for (int i=1; i)
            queue[i] = null;

        size = 0;
    }

    private void fixUp(int k) {//维护最小堆
        while (k > 1) {
            int j = k >> 1;
            if (queue[j].nextExecutionTime  queue[k].nextExecutionTime)
                break;
            TimerTask1 tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

    private void fixDown(int k) {
        int j;
        while ((j = k << 1)  0) {
            if (j < size &&
                queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
                j++; // j indexes smallest kid
            if (queue[k].nextExecutionTime  queue[j].nextExecutionTime)
                break;
            TimerTask1 tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

    void heapify() {
        for (int i = size/2; i >= 1; i--)
            fixDown(i);
    }
}

Original: https://www.cnblogs.com/yaowen/p/13431627.html
Author: 哈哈呵h
Title: Timer

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/546755/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • http代理连接

    基于Linux服务器的http代理连接 1. 准备工作 &#x76EE;&#x6807;&#x670D;&#x52A1;&#x5668; &…

    技术杂谈 2023年6月21日
    083
  • java基础

    深入循环结构 for(循环条件1) { //循环操作1 for(循环条件2) { //循环操作2 } } 多层循环: 外层循环变量变化一次,内层循环变量要变化一轮。 一、循环打印输…

    技术杂谈 2023年7月11日
    050
  • 企业级仓库Harbor高可用方案【转】

    一、Harbor产品介绍 Harbor 是 VMware公司开源的企业级 Docker Registry 项目,其日标是帮助用户迅速搭建一个企业级的 Docker Registry…

    技术杂谈 2023年5月31日
    0106
  • 电商WMS介绍

    其他竞品 今天先到这儿,希望对云原生,技术领导力, 企业管理,系统架构设计与评估,团队管理, 项目管理, 产品管管,团队建设 有参考作用 , 您可能感兴趣的文章: 如有想了解更多软…

    技术杂谈 2023年6月1日
    078
  • 工业软件技术的总结和开发方向

    以前总结了一回工业应用的技术栈方向,生成了一个技术导图已经做了罗列规划,内容也基本上包含了普通应用所需要的大部分方面,当然可能对于个人的技术见识来说会有遗漏空缺,这个还需要到具体项…

    技术杂谈 2023年7月23日
    073
  • 解决计划任务bat脚本中涉及网络位置时遇到的问题

    解决掉困扰几天的bug神清气爽,赶紧来写篇随笔~ 前几天由于安全原因把一个Windows Server 2012 R2上的本地硬盘SFTP换成了一个NAS SFTP 然后理所当然的…

    技术杂谈 2023年7月11日
    057
  • 开源基础框架csx-bsf-all【开源】【原创】

    Git地址 技术架构 BSF 为 base service framework 的简写,定义为技术团队的基础框架,用于基础服务的集成和跟业务无关的基础技术集成。 BSF集成了自研的…

    技术杂谈 2023年7月23日
    050
  • Java函数式编程

    Java函数式编程 初探函数式编程【JavaScript篇】_哔哩哔哩_bilibili 三更草堂Up主。不会Lambda表达式、函数式编程?你确定能看懂公司代码?-java8函数…

    技术杂谈 2023年7月11日
    087
  • 网络设备配置-8、利用ospf配置动态路由

    一、前言 同系列前几篇:网络设备配置–1、配置交换机enable、console、telnet密码网络设备配置–2、通过交换机划分vlan网络设备配置&#8…

    技术杂谈 2023年7月11日
    051
  • SETTLE约束算法中的坐标变换问题

    技术背景 在之前的两篇文章中,我们分别讲解了SETTLE算法的原理和基本实现和SETTLE约束算法的批量化处理。SETTLE约束算法在水分子体系中经常被用到,该约束算法具有速度快、…

    技术杂谈 2023年7月25日
    052
  • mongo笔记

    获取stats from pymongo import MongoClient client = MongoClient() db = client.test print coll…

    技术杂谈 2023年7月11日
    056
  • MySQL版本引起的错误

    接上一篇帖子,博主在CentOS上安装了最新版的MySQL容器(版本为8.0.19),在使用本地springBoot项目连接,启动项目后操作登录系统时报错。 请看代码: com.m…

    技术杂谈 2023年7月25日
    051
  • RabbitMQGUI客户端工具(RabbitMQAssistant)

    RabbitMQ GUI客户端工具(RabbitMQ Assistant) 平时用控制台或者网页进行管理不免有点不方便,尤其在读取消息的时候不支持过滤和批量发送消息,在此推荐一个漂…

    技术杂谈 2023年7月24日
    062
  • 2-ESP8266转CAN总线和RS232通讯模块-CAN总线通信测试Arduino

    说明 这里测试其中一块板子和另一块板子进行CAN总线通信(用户可以接其它CAN总线设备) 测试 1.解压.rar文件 2.把下面三个文件放到安装的ESP8266的库文件夹里面 3….

    技术杂谈 2023年6月1日
    081
  • 枚举进行位运算 枚举组合z

    public enum MyEnum { MyEnum1 = 1, //0x1 MyEnum2 = 1 << 1, //0x2 MyEnum3 = 1 <<…

    技术杂谈 2023年6月1日
    064
  • 从SpringBoot启动,阅读源码设计

    一、背景说明 二、SpringBoot工程 三、应用上下文 四、资源加载 五、应用环境 六、Bean对象 七、Tomcat服务 八、事件模型 九、配置加载 十、数据库集成 十一、参…

    技术杂谈 2023年7月23日
    046
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球