Java Essay one (timer source code analysis and use of scheduleatfixedrate)

Source: Internet
Author: User
Tags terminates

Write the basic article, think for a long time to write into the order of the article. To write JSP and so on usage. Finally decided not to write. Because he is not a Java-related Daniel. At the moment also to do while learning, so decided to first do not understand their own to learn and write down.

A timer is a Java-brought Java.util.Timer class that dispatches a Java.util.TimerTask task. This way, the program can run at a certain frequency.


1, the Timer class source code Analysis:

public class Timer {    /**     * The timer task queue.  This data structure is a shared with the timer     * thread.  The timer produces tasks, via its various schedule calls,     * and the timer thread consumes, executing timer tasks as AP Propriate,     * and removing them from the queue when they ' re obsolete.     *    /private Taskqueue queue = new Taskqueue ();    /**     * The timer thread.     *    /private TimerThread thread = new TimerThread (queue);
First the timer class defines two private variables taskqueue and TimerThread.


taskqueue:The Timer class defines a timer task queue. A Timertasks priority queue.

Class Taskqueue {    /**     * Priority queue represented as a balanced binary heap:the both children     * of Queue[n] A Re queue[2*n] and queue[2*n+1].  The priority queue was     * 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];

The task of the Timerthread:timer class runs the thread. Inherits from the thread class. Take Taskqueue as the number of references.


When using the Timer class, first new a Timer object and then run the task with the SCHEDULEXXX function, first analyzing the Timer object construction process:

Public Timer () {This ("timer-" + serialnumber ()); }
    Public Timer (Boolean Isdaemon) {This ("timer-" + serialnumber (), Isdaemon); }<span style= "White-space:pre" ></span>
    Public Timer (String name) {        thread.setname (name);        Thread.Start ();    }
    Public Timer (String name, Boolean Isdaemon) {        thread.setname (name);        Thread.setdaemon (Isdaemon);        Thread.Start ();    }
It can be seen that the timer needs to start a timerthread thread during the construction of the object, so it can be pushed,The timerthread thread and the timer object work together to maintain a taskqueue, using taskqueue for information transfer.

Next look at the SCHEDULEXXX function. All schedulexxx functions need to call the Sched method,

private void Sched (TimerTask task, long time, long period) {        if (Time < 0)            throw new IllegalArgumentException (" Illegal execution time. ");        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 ();}    }
Here first introduce the TimerTask class:

Public abstract class TimerTask implements Runnable {    /**     * This object was used to control access to the TimerTask Internals.     *    /Final Object lock = new Object ();

The TimerTask class implements the Runnable interface, and the task to be run is placed in run (). When constructing a timed task. Inherit from TimerTask and implement the Run method. and create a task to pass to the schedulexxx method.

As can be seen from the Sched method, theSched method needs to operate the Taskqueue queue, and the TimerThread thread starts to use the same queue. This must be done using synchronized to ensure that multithreading is safe to use.

2, the use of schedulexxx:

The principle of the timer class is very easy and there are not many functions that can be used. The following will all be listed.

(1) Void Java.util.Timer.schedule (timertask task, long delay): how long (milliseconds) to run the task

(2) void Java.util.Timer.schedule (timertask task, Date time): Sets a task to run

(3) void Java.util.Timer.schedule (timertask task, long delay, long period): Runs the task after the delay time and invokes the task once every period time.

(4) Void Java.util.Timer.schedule (timertask task, Date Firsttime, long period): The first time you run a task at a specified firsttime point, The task is invoked once every period time.

(5) Void Java.util.Timer.scheduleAtFixedRate (timertask task, long delay, long period): Starts running the task after the delay time. and call the task once every period time.

(6) Void Java.util.Timer.scheduleAtFixedRate (timertask task, Date Firsttime, long period): Runs the task for the first time at the specified Firsttime point The task is invoked once every period time.

(7) void Java.util.Timer.cancel (): Terminates the Timer

(8) Boolean java.util.TimerTask.cancel (): Terminates the TimerTask

among these schedulexxx methods, except (1) (2), the other is able to invoke the task repeatedly, the basic difference is the difference between schedule and scheduleatfixedrate.


The schedule () method is more focused on maintaining the stability of the interval time: guaranteed to be called once every period time.


The Scheduleatfixedrate () method is more focused on keeping the operating frequency stable: The frequency of multiple calls is approaching period time. Assuming that a call time is greater than period, the next one will be as small as period. To guarantee frequency close to period


3, the use of the Timer class display column

First create a task:

<pre name= "code" class= "Java" >import Java.util.timertask;public class MyTask extends timertask{     private int ID;     Public mytask (int id) {         this.id = ID;     }     public void Run () {         System.out.println ("thread" + ID + ": Running");         System.GC ();     }}

Main function Code:

Import Java.util.date;import Java.util.timer;public class test{public    static void Main (string[] args) {        Timer Timer = new timer ();        Timer.schedule (New MyTask (1), 5000);//5 Seconds after starting task        mytask secondtask = new MyTask (2);        Timer.schedule (Secondtask, n, +);        Start the task after 1 seconds, run the thread every 3 seconds at a time date        = new Date ();        Timer.schedule (New MyTask (3), New Date (Date.gettime () + +));      specify a point in time to run the thread        //      Timer.cancel () with date as a parameter;      Secondtask.cancel ();        System.out.println ("Main thread ends!");}        }



Java Essay one (timer source code analysis and use of scheduleatfixedrate)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.