Write the basic article, think for a long time to write into the order, to write JSP and so on the use of the method, and finally decided not to write, because he is not the Java side of the Daniel, at the moment to do while learning, so decided to take out their own do not understand to learn and write down.
A timer is a Java-brought Java.util.Timer class that dispatches a Java.util.TimerTask task. This approach allows the program to execute 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 execution thread of the Timerthread:timer class inherits from the thread class. Take taskqueue as the parameter.
When using the Timer class, first new a Timer object, and then using the SCHEDULEXXX function to perform the task, first analyze 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 (); }
As you can see, the timer needs to start a timerthread thread during the construction of the object, so you can guess,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 executed 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 simple, you can use a few functions, the following will be all listed.
(1) Void Java.util.Timer.schedule (timertask task, long delay): how long (milliseconds) to perform a task
(2) void Java.util.Timer.schedule (timertask task, Date time): Set a period to perform a task
(3) void Java.util.Timer.schedule (timertask task, long delay, long period): After the delay time, the task is started and the task is called every period time.
(4) Void Java.util.Timer.schedule (timertask task, Date Firsttime, long period): The first time a task is executed 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): Start 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): The first time a task is executed at a 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
of these schedulexxx methods, except (1) (2), the other can be called repeatedly, the main 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 maintaining the stability of the execution frequency: The frequency of multiple calls is approaching period time, if one call time is greater than period, the next one will be less than period, to ensure that the frequency is 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 + ": executing"); 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, and execute 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 execution thread // Timer.cancel () with date as parameter; Secondtask.cancel (); System.out.println ("Main thread ends!");} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Essay one (timer source analysis and the use of scheduleatfixedrate)