ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

定时器Timer源码解析

2021-12-27 14:33:24  阅读:125  来源: 互联网

标签:定时器 thread Timer task queue 源码 线程 执行


定时器Timer源码解析

一 Timer

1、Timer

Timer较之Quartz结构相对简单,其原理更容易动,并且两个会有相似之处,可以在了解Timer之后在看Quartz可能会相对容易通透一点,在Quartz之前先了解一下Timer定时器,以下是JDK Api中的介绍:

  • 线程调度任务以供将来在后台线程中执行的功能。 任务可以安排一次执行,或定期重复执行。
  • 对应于每个Timer对象是单个后台线程,用于依次执行所有定时器的所有任务。 计时器任务应该快速完成。 如果一个定时器任务需要花费很多时间来完成,它会“计时”计时器的任务执行线程。 这可能会延迟随后的任务的执行,这些任务在(和)如果违规任务最后完成时,可能会“束起来”并快速执行。
  • 在最后一次对Timer对象的引用后*,所有未完成的任务已完成执行,定时器的任务执行线程正常终止(并被收集到垃圾回收)。但是,这可能需要任意长时间的发生。默认情况下,任务执行线程不作为守护程序线程*运行,因此它能够使应用程序终止。如果主叫方想要快速终止定时器的任务执行线程,则调用者应该调用定时器的cancel方法
  • 这个类是线程安全的:多个线程可以共享一个单独的Timer对象,而不需要外部同步。
  • 如果定时器的任务执行线程意外终止,例如,因为它调用了stop方法,那么在计时器上安排任务的任何进一步的尝试将会产生一个IllegalStateException ,就像定时器的cancel方法被调用一样。

2、源码解析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xucriyys-1640585714901)(C:\Users\xiang'hong'fei\AppData\Roaming\Typora\typora-user-images\image-20211227104528157.png)]

2.1 Timer

​ 初始化Timer时,会将其中的TaskQueue以及TimerThread也进行相应的初始化并且,会启动线程,使thread在一个wait状态。

   /**
     * 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);
	/**
     * Creates a new timer whose associated thread has the specified name.
     * The associated thread does <i>not</i>
     * {@linkplain Thread#setDaemon run as a daemon}.
     *
     * @param name the name of the associated thread
     * @throws NullPointerException if {@code name} is null
     * @since 1.5
     */
	//初始化时会将thead线程启动,使其在一个wait状态。
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }
	/**
     * Schedules the specified task for execution after the specified delay.
     *
     * @param task  task to be scheduled.
     * @param delay delay in milliseconds before task is to be executed.
     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
     *         <tt>delay + System.currentTimeMillis()</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     * @throws NullPointerException if {@code task} is null
     */
    public void schedule(TimerTask task, long delay) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        sched(task, System.currentTimeMillis()+delay, 0);
    }

​ 其中的核心schedule方法提供多个重载方法,提供给使用者,最终会调用sched方法。参数含义如下:task(具体执行动作),time(下一次执行时间),perid(每次执行时间间隔)。

 	/**
     * Schedule the specified timer task for execution at the specified
     * time with the specified period, in milliseconds.  If period is
     * positive, the task is scheduled for repeated execution; if period is
     * zero, the task is scheduled for one-time execution. Time is specified
     * in Date.getTime() format.  This method checks timer state, task state,
     * and initial execution time, but not period.
     
     * 计划指定的计时器任务,以便在指定的时间和指定的时间段执行,以毫秒为单位。
     * 如果周期为正,则计划重复执行任务;如果周期为零,则计划一次性执行任务。
     * 时间以日期指定。getTime()格式。此方法检查计时器状态、任务状态、和初始执行时间,但不检查周期。
     *
     * @param task 具体执行动作。
     * @param time 下次执行时间,时间戳。
     * @param period 每次执行时间间隔,时间戳。
     */
    private void sched(TimerTask 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;
		//同一个Timer并发调用sched时加重锁
        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");
			//不同Timer调用同一个task时,task加锁应用,task.lock为TimerTask类中的加锁标识。
            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;
            }
			//将task加入执行计划queue中。
            queue.add(task);
            if (queue.getMin() == task)
                //getMin()获取执行计划中下一次执行,如果当前task为下次执行,则通知queue,不需要在wait
                queue.notify();
        }
    }

2.2 TimerThread(thread)

TimerThread主要用于管理task重复的启用以及非重复task任务的删除,在上述Timer中,初始化时会启动以下线程,使thread到达运行状态,执行mainLoop方法,进而在该方法中在到等待状态。

	/**
     * 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!
     */
	//是否继续执行,true标识继续,false标识结束,最终结束定时器,还需要清空执行计划queue。
    boolean newTasksMayBeScheduled = true;
	/**
     * Our Timer'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
            //上述mainLoop执行结束
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }

    /**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            //??????无线执行for循环完成自动服务。		
            try {
                TimerTask task;
                boolean taskFired;
                //将一个执行计划queue,初始化多个TimerThread,并启动线程时,需要将queue加锁
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        //执行计划中五可执行任务,并且为可执行状态时,则执行计划等待任务加入
                        queue.wait();
                    if (queue.isEmpty())
                        //如果如果queue为空,则退出不在进行,clear时
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    //executionTime 下一次执行时间
                    long currentTime, executionTime;
                    //获取下一次执行计划
                    task = queue.getMin();
                    //场景同一个task列入多个执行计划时,
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            //task状态为取消状态时,queue执行计划需要将task删除,并将queue按下一次执行时间进行排序。
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            //taskFired(true) 下次执行时间小于等于当前时间时
                            if (task.period == 0) { // Non-repeating, remove
                                //不存在时间间隔时,并且次执行时间小于等于当前时间时,标识非重复任务,则将之从执行计划中删除
                                queue.removeMin();
                                //并更新该task的执行状态
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                //改task任务为重复执行任务,则更新下次执行时间,并且将queue执行计划按下次执行时间进行排序。
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn't yet fired; wait
                        //taskFired(false) 下次执行时间大于当前时间时,则等待
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    //满足条件则执行task
                    task.run();
            } catch(InterruptedException e) {
            }
        }
    }

2.3 TaskQueue(queue)

    /**
     * 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.
     */
    //默认数组长度128
	private TimerTask[] queue = new TimerTask[128];
	/**
     * Adds a new task to the priority queue.
     */
	//判断长度,并采用数组扩容
    void add(TimerTask task) {
        // 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];
    }
	/**
     * 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);
    }
	/**
     * 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);
    }
	/**
     * 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's).
     *
     * This method functions by "promoting" queue[k] up the hierarchy
     * (by swapping it with its parent) repeatedly until queue[k]'s
     * nextExecutionTime is greater than or equal to that of its parent.
     */
	//将将执行计划queue[k]与queue[1]进行比较,执行计划靠前的则放入queue[1]中
    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's).
     *
     * This method functions by "demoting" queue[k] down the hierarchy
     * (by swapping it with its smaller child) repeatedly until queue[k]'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 < size && queue[j].nextExecutionTime > 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;
        }
    }

简单示例

public class SimpleTimer {
  public static void main(String[] args) {
    Timer simpleTimer = new Timer("firstTime");

    SimpleTask task = new SimpleTask();
    //Object lock = new Object();
    //1000毫秒后开始执行,每次间隔2000毫秒
    simpleTimer.schedule(task,1000,2000);
    simpleTimer.schedule(task,1000,2000);

  }


  public static class SimpleTask extends TimerTask{
    Integer index = 0;

    @Override
    public void run() {
      index = index + 1;
      System.out.println("************"+index);
      if(index == 10 ){
        cancel();
      }
    }

  }
}

注:由于Timer采用单线程执行,未采用线程池,在遇到耗时较长的Job工作时,时间校准会出现误差

标签:定时器,thread,Timer,task,queue,源码,线程,执行
来源: https://blog.csdn.net/drop616/article/details/122171120

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有