热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

【源码】Timer和TimerTask源码剖析

Timer是java.util包中的一个工具类,提供了定时器的功能。我们可以构造一个Timer对象,然后调用其schedule方法在某个特定的时间或者若干延时之后去执行一个特定的任务,甚至你可以让其以特定频率一直执行某个任务,这个任务用TimerTask描述,我们将需要的操作写在TimerTask类的run方法中即可。
Timer是java.util包中的一个工具类,提供了定时器的功能。我们可以构造一个Timer对象,然后调用其schedule方法在某个特定的时间或者若干延时之后去执行一个特定的任务,甚至你可以让其以特定频率一直执行某个任务,这个任务用TimerTask描述,我们将需要的操作写在TimerTask类的run方法中即可
本着“知其然,知其所以然”的心态,我决定研究下这个类的源码。

打开Timer类的源码我发现了这样两个成员变量:

 /**
     * The timer task queue.  This data structure is shared with the timer
     * thread.  The timer produces tasks, via its various schedule calls,
     * and the timer thread consumes, executing timer tasks as appropriate,
     * and removing them from the queue when they're obsolete.
     */
    private final TaskQueue queue = new TaskQueue();//任务队列
    /**
     * The timer thread.
     */
    private final TimerThread thread = new TimerThread(queue);//执行线程

TaskQueue是一个优先级队列,存放了我们将要执行的TimerTask对象,TimerTask对象是通过Timer类的一系列schedule方法加入队列的,TimerThread负责不断取出TaskQueue中的任务,然后执行之,也就是说,所有的任务都是是在子线程中执行的。TaskQueue队列是以其下次执行时间的先后排序的,TimerThread每次取出的都是需要最先执行的TimerTask。(跟android中的Handler机制很类似~)
优先级队列跟普通队列的最大区别就是,优先级队列每次出队的都是优先级最高的元素,并不是按先进先出的方式。这里优先级队列的实现使用的是堆结构(当然,你也可以使用普通链表,但是每次出队得花O(n)的时间遍历链表找到优先级最大的元素,不划算),插入及更新操作都能维持在O(logn):
class TaskQueue {
    /**
     * Priority queue represented as a balanced binary heap: the two children
     * of queue[n] are queue[2*n] and queue[2*n+1].  The priority queue is
     * ordered on the nextExecutionTime field: The TimerTask with the lowest
     * nextExecutionTime is in queue[1] (assuming the queue is nonempty).  For
     * each node n in the heap, and each descendant of n, d,
     * n.nextExecutionTime <= d.nextExecutionTime.
     */
    private TimerTask[] queue = new TimerTask[128];//使用数组存储堆元素,最大值128
    /**
     * The number of tasks in the priority queue.  (The tasks are stored in
     * queue[1] up to queue[size]).
     */
    private int size = 0;//任务数
    /**
     * Returns the number of tasks currently on the queue.
     */
    int size() {
        return size;
    }
    /**
     * Adds a new task to the priority queue.
     */
    void add(TimerTask task) {//将TimerTask任务添加到此队列中
        // Grow backing store if necessary
        if (size + 1 == queue.length)
            queue = Arrays.copyOf(queue, 2*queue.length);
        queue[++size] = task;
        fixUp(size);//调整堆结构---->所谓的上滤
    }
    /**
     * Return the "head task" of the priority queue.  (The head task is an
     * task with the lowest nextExecutionTime.)
     */
    TimerTask getMin() {//优先级最高的元素始终在第一个位置
        return queue[1];
    }
    /**
     * Return the ith task in the priority queue, where i ranges from 1 (the
     * head task, which is returned by getMin) to the number of tasks on the
     * queue, inclusive.
     */
    TimerTask get(int i) {
        return queue[i];
    }
    /**
     * Remove the head task from the priority queue.
     */
    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 <= i <= size.
     */
    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);
    }
    /**
     * Returns true if the priority queue contains no elements.
     */
    boolean isEmpty() {
        return size==0;
    }
    /**
     * Removes all elements from the priority queue.
     */
    void clear() {
        // Null out task references to prevent memory leak
        for (int i=1; i<=size; i++)
            queue[i] = null;
        size = 0;
    }
    /**
     * Establishes the heap invariant (described above) assuming the heap
     * satisfies the invariant except possibly for the leaf-node indexed by k
     * (which may have a nextExecutionTime less than its parent&#39;s).
     *
     * This method functions by "promoting" queue[k] up the hierarchy
     * (by swapping it with its parent) repeatedly until queue[k]&#39;s
     * nextExecutionTime is greater than or equal to that of its parent.
     */
    private void fixUp(int k) {
        while (k > 1) {
            int j = k >> 1;
            if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }
    /**
     * Establishes the heap invariant (described above) in the subtree
     * rooted at k, which is assumed to satisfy the heap invariant except
     * possibly for node k itself (which may have a nextExecutionTime greater
     * than its children&#39;s).
     *
     * This method functions by "demoting" queue[k] down the hierarchy
     * (by swapping it with its smaller child) repeatedly until queue[k]&#39;s
     * nextExecutionTime is less than or equal to those of its children.
     */
    private void fixDown(int k) {
        int j;
        while ((j = k <<1) <= size && j > 0) {
            if (j  queue[j+1].nextExecutionTime)
                j++; // j indexes smallest kid
            if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }
    /**
     * Establishes the heap invariant (described above) in the entire tree,
     * assuming nothing about the order of the elements prior to the call.
     */
    void heapify() {//建堆操作,从第一个非叶子结点开始。
        for (int i = size/2; i >= 1; i--)
            fixDown(i);
    }
}

TaskQueue内部是一个TimerTask数组,数组元素从1开始,这个数组就是所谓的堆,还是个小顶堆,堆顶元素
始终为第一个元素,每次添加TimerTask都会调用fixup上滤操作,维持堆的特性,每次删除堆顶元素后需要调用fixdown下滤操作,维持堆的特性。heapify是一个建堆函数(类&#20284;堆排序中的建堆操作),从第一个非叶子结点开始。

了解TaskQueue后,再看TimerThread类:
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&#39;s monitor!
     */
    boolean newTasksMayBeScheduled = true;
    /**
     * Our Timer&#39;s queue.  We store this reference in preference to
     * a reference to the Timer so the reference graph remains acyclic.
     * Otherwise, the Timer would never be garbage-collected and this
     * thread would never go away.
     */
    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
            }
        }
    }
    /**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {//死循环
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {//线程安全
                    // Wait for queue to become non-empty
                    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();//取出优先级最高的任务
                    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&#39;t yet fired; wait
                        queue.wait(executionTime - currentTime);//没到执行时间久等待
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();//执行该任务
            } catch(InterruptedException e) {
            }
        }
    }
}

注释写的很明白,TimerThread会在run方法中调用mainloop方法,这是一个死循环,不断从任务队列中取出任务,执行之,如果没有任务可执行,将会wait,等待队列非空,而Timer类的schedule方法会调用notify唤醒该线程,执行任务。

private void sched(TimerTask task, long time, long period) {//所有的schedule方法都会调用此方法
        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 != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutiOnTime= time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }
            queue.add(task);//加入任务队列
            if (queue.getMin() == task)
                queue.notify();//唤醒任务执行线程
        }
    }

那么TimerThread何时被启动的呢?猜猜也能知道,肯定是Timer被创建时执行的:

public Timer(String name) {
        thread.setName(name);
        thread.start();//启动线程
    }

当我们主线程执行完毕后,Timer线程可能仍然处于阻塞或者其他状态,有时这不是我们希望看到的,Timer类有这样一个构造器,可以让任务执行线程以守护线程的方式运行,这样当主线程执行完毕后,守护线程也会停止。
 public Timer(boolean isDaemon) {
        this("Timer-" + serialNumber(), isDaemon);
    }

以上就是Timer类的源码分析过程,最后贴上一张图,帮助理解:



推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
author-avatar
手机用户2602881147
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有