Java Implementation Timers Timer

Source: Internet
Author: User
Tags thread class thread stop

Java Implementation Timers Timer

1. Timer and TimerTask
    • The timer is a timer tool provided in the JDK that uses a single thread that executes the specified scheduled task outside the main thread, and can be executed once or repeatedly.

    • TimerTask is an abstract class that implements the Runnable interface, representing a task that can be performed by a timer.


2. An example of a timer dispatch

Implementing a Task

Package Com.usoft.timer;import Java.util.timertask;public Class Task extends TimerTask {public void run () {Sys    TEM.OUT.PRINTLN ("Timed task execution, taskid=" + This.hashcode ()); }}

Test timer

Package com.usoft.timer;import java.util.calendar;import java.util.timer;public class  timetasktest {    public static void main (String[] args)  throws interruptedexception {        timer timer  = new timer ();         timer.schedule (New Task (),  10 * 1000); //10  second delay execution         timer.schedule (New task (),  60 * 1000, 10 * 1000);//60  seconds delay execution, executed once every 10 seconds          calendar c = calendar.getinstance ();         c.add (calendar.millisecond, 1000 * 60);         timer.schedule (New task (),  c.gettime ())  //the current time 60 seconds after execution          Timer.schedule (New task (),  c.gettime (),  10 * 1000);         timer.scheduleatfixedrate (New task (),  c.gettime (),  10 * 1000);         timer.scheduleatfixedrate (New task (),  60 *  1000, 10 * 1000);         thread.sleep (1000 *  120);         timer.cancel ();//timer stops running     }}


3. How to terminate a timer thread

By default, the timer thread that is created is executed all the time, with the following four ways to terminate the timer thread:

    • Call the timer's Cancle method

    • Set the timer thread to the daemon thread, (new timer (true) creates the daemon thread), and in the JVM, if all the user threads end, the daemon thread will be terminated, but this method is generally not used.

    • When all tasks have been executed, a reference to the corresponding timer object is deleted and the thread is terminated.

    • Call the System.exit method to terminate the program


4. About Cancle way to terminate a thread

This way to terminate the timer thread, the JDK implementation is quite ingenious, say a little bit.

First look at the source code of Cancle method:

Copy Code

public void Cancel () {synchronized (queue) {thread.newtasksmaybescheduled = false;        Queue.clear ();  Queue.notify ();    In case the queue was already empty. }}

Copy Code

Without an explicit thread stop method, instead of invoking the clear method of the queue and the Notify method of the queue, clear is a custom method, and notify is the Objec method, obviously to wake the wait method.

Then look at the Clear method:

void Clear () {//Null out task references to prevent memory leak for (int i=1; i<=size; i++) queue[i] = n    Ull size = 0;}

The clear method is simple, that is, to clear the Queue,queue is an array of timertask, and then reset the size of the queue to 0, to empty. Or you don't see an explicit stop threading method, go back to the beginning of the new timer and look at the new Timer Code:

Public Timer () {This ("timer-" + serialnumber ());}    Public Timer (String name) {thread.setname (name); Thread.Start ();}

Look at this internal variable, thread:

/** * the timer thread. */private final TimerThread thread = new TimerThread (queue);

is not a native thread, it is a custom class TimerThread. This class implements the thread class, overriding the Run method, as follows:

public void Run () {try {mainloop (); } finally {//Someone killed this Thread, behave as if Timer cancelled synchronized (queue) {New            tasksmaybescheduled = false;  Queue.clear (); Eliminate obsolete References}}}

The last is this mainloop method, which is longer,

/** * 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 ' t yet fired; wait                     queue.wait ( Executiontime - currenttime);             }            if  (taskfired)     Task fired; run it, holding no locks                 task.run ();         } catch (Interruptedexception e)  {        }     }}

You can see the wait method, the previous notify is to notify this wait, and then the clear method notify the array before the operation, so it will break, the thread execution ends, exit.


5. Perform a task repeatedly

Implemented by invoking the schedule method of three parameters, the last parameter is the execution interval, in milliseconds.


6. Schedule VS. Scheduleatfixedrate

Both methods are task scheduling methods, the difference between them is that schedule will ensure that the interval of the task is strictly performed according to the defined period parameters, if a time schedule is longer, then the subsequent time will be postponed, to ensure that the scheduling interval is period, And Scheduleatfixedrate is strictly in accordance with the scheduling time, if a scheduling time is too long, then by shortening the interval to ensure that the next scheduled time to execute. For a chestnut: you dispatch every 3 seconds, then normal is 0,3,6,9s such a time, if the second schedule spent 2s of time, if it is schedule, will become 0,3+2,8,11 such time, guarantee interval, And Scheduleatfixedrate will become 0,3+2,6,9, compression interval, to ensure the scheduling time.


7. Some points of attention

Each timer only corresponds to a single thread.

The timer does not guarantee that the task executes very precisely.

The Timer class is thread-safe.

==============================end==============================

Java Implementation Timers Timer

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.