The--timer and Scheduledexecutorservice__java of Java

Source: Internet
Author: User

Reprint please indicate the source: http://blog.csdn.net/l1028386804/article/details/48050505

The Java.util.Timer timer has administrative tasks deferred execution ("Perform tasks like 1000ms") and periodic execution ("such as perform this task every 500ms"). However, there are some drawbacks to the timer, so you should consider using Scheduledthreadpoolexecutor as a substitute, and the timer's support for scheduling is based on absolute time, not relative time,
This task is sensitive to the change of the system clock; Scheduledthreadexecutor only supports relative time.

Another problem with a timer is that if TimerTask throws an unchecked exception, the timer will produce unpredictable behavior.
The timer thread does not catch exceptions, so an unchecked exception thrown by TimerTask terminates the timer thread.
In this case, the timer does not restore the execution of the thread again; it mistakenly thinks the whole timer has been canceled.
At this point, TimerTask, which has been scheduled but not yet executed, will never be executed, and new tasks cannot be scheduled.
 

Personal Summary: Timer bug:60 seconds, if the user changed the time then the hand will be 0, is close to 10 seconds when the timer will be timed again and then 60 before implementation.

Test Timer Example:

package com.lyz.test;  
Import Java.util.Timer;  
Import Java.util.TimerTask;  
    /** * Test Timer Sample program * @author Liuyazhuang */public class Timertest {Private Timer timer = new timer ();  
                Start timer public void Lanuchtimer () {Timer.schedule (New TimerTask ()} {public void run () {  
            throw new RuntimeException ();  
    }, 1000*3, 500); ///Add a task to the timer public void Addonetask () {timer.schedule () {The new TimerTask () {public void R  
            Un () {System.out.println ("Hello World");  
    }}, 1000*1,1000*5);  
        public static void Main (string[] args) throws Exception {timertest test = new Timertest ();  
        Test.lanuchtimer ();  
    Thread.Sleep (1000*5);//5 Seconds later add a new task Test.addonetask (); }  
}
Running the program, the Timer throws a rumtimeexception and Java.lang.IllegalStateException:Timer already cancelled.
As the saying goes, it's a double whammy the timer also transmitted its problem to the next hapless caller, who had tried to submit a timertask, you might want the program to run all the time, but the actual situation was aborted after 5 seconds in the program, followed by an exception, and the exception message was " Timer already cancelled ". Scheduledthreadpoolexector handled this unusual task properly, so there is little reason to use the timer in java5.0 or higher jdk.

The test results of the timer are shown in the picture

Examples of improvements with Scheduledthreadpoolexector

Package com.lyz.test;  
Import java.util.concurrent.Executors;  
Import Java.util.concurrent.ScheduledExecutorService;  
  
Import Java.util.concurrent.TimeUnit; /** * Scheduledthreadpoolexector Test program * @author Liuyazhuang * */public class Scheduledexecutortest {//thread pool can be scheduled by time To perform a task that allows the user to set the time when the task is scheduled to be performed, and the parameter of type int is the minimum number of threads in the set//thread pool.
    When more tasks are available, the thread pool may automatically create more worker threads to perform tasks//It is better to use Executors.newsinglethreadscheduledexecutor () here.  
    Public Scheduledexecutorservice scheduexec = Executors.newscheduledthreadpool (1);  
                Start timer public void Lanuchtimer () {Runnable task = new Runnable () {public void run () {  
            throw new RuntimeException ();  
        }  
        };  
    Scheduexec.schedulewithfixeddelay (Task, 1000*5, 1000*10, timeunit.milliseconds);  //Add New Task public void Addonetask () {Runnable task = new Runnable () {public void run ()  {System.out.println ("Welcome to");
            }  
        };  
    Scheduexec.schedulewithfixeddelay (Task, 1000*1, 1000, timeunit.milliseconds); public static void Main (string[] args) throws Exception {scheduledexecutortest test = new schedu  
        Ledexecutortest ();  
        Test.lanuchtimer ();  
    Thread.Sleep (1000*5);//5 Seconds later add New Task Test.addonetask (); }  
}
As you can see from the screenshot below, even if an exception inside the timer doesn't affect the normal call, you don't have to worry about scheduleexecutor an exception that causes the timer to stop, and the timer stops because of the exception.





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.