In our programming process, if we need to execute some simple timing tasks without complicated control, we can consider using the Timer timing task in JDK. The following LZ resolves the java Timer in terms of its principle, instance, and Timer defect.
I. Introduction
In java, a complete scheduled task must be completed by the Timer and TimerTask classes. They are defined in the API in this way. Timer is a tool used by a thread to schedule tasks to be executed in the background thread. You can schedule the task to be executed once, or perform the task repeatedly on a regular basis. Scheduled by TimerTask: Timer is a task executed or repeated. We can understand this.Timer is a Timer tool used to plan to execute a specified task in a background thread, while TimerTask is an abstract class. Its subclass represents a task that can be scheduled by Timer.
Timer class
In the tool class Timer, four constructor methods are provided. Each constructor starts a Timer thread. At the same time, the Timer class ensures that multiple threads can share a single Timer object without external synchronization, therefore, the Timer class is thread-safe. However, since each Timer object corresponds to a single background thread, it is used to execute all Timer tasks in sequence. In general, the time consumed for executing our thread tasks should be very short, however, due to special circumstances, the execution time of a timer task is too long, so it will "exclusively" The task execution thread of the timer, and all subsequent threads must wait for it to complete, this will delay the execution of subsequent tasks, so that these tasks are stacked together. We will analyze the details later.
After the Timer Program Initialization is complete, the scheduled task will be executed according to the preset time. Timer provides the schedule method, which can be overloaded in multiple ways to adapt to different situations, as shown below:
Schedule (TimerTask task, Date time): scheduled to run the specified task at the specified time.
Schedule (TimerTask task, Date firstTime, long period): schedule the specified task to start repeating fixed delay execution at the specified time.
Schedule (TimerTask task, long delay): scheduled to run the specified task after the specified delay.
Schedule (TimerTask task, long delay, long period): schedule the specified task to start repeated fixed delay execution after the specified delay.
At the same time, the scheduleAtFixedRate method is also overloaded. The scheduleAtFixedRate method is the same as schedule, but their focus is different. The difference is analyzed later.
ScheduleAtFixedRate (TimerTask task, Date firstTime, long period): Schedule the specified task to start repeating at a fixed rate.
ScheduleAtFixedRate (TimerTask task, long delay, long period): schedules a specified task to start repeated execution at a fixed rate after the specified delay.
TimerTask
The TimerTask class is an abstract class that is scheduled by Timer to be executed at one time or repeatedly. It has an abstract method run (), which is used to execute the operations to be performed by the corresponding timer task. Therefore, each specific task class must inherit TimerTask and then override the run () method.
There are also two non-Abstract METHODS:
Boolean cancel (): cancels this timer task.
Long scheduledExecutionTime (): return the scheduled execution time of the task.
Ii. instance 2.1: scheduled task execution with specified latency
Public class TimerTest01 {Timer timer; public TimerTest01 (int time) {timer = new Timer (); timer. schedule (new TimerTaskTest01 (), time * 1000 );}</Span> <span> public class TimerTaskTest01 extends TimerTask {</Span> <span> first print: timer begin... 3 seconds later print: Time's up !!!!
2.2 execute a scheduled task at a specified timePublic class TimerTest02 {Timer timer; public TimerTest02 () {Date time = getTime (); System. out. println ("specified time =" + time); timer = new Timer (); timer. schedule (new TimerTaskTest02 (), time);} public Date getTime () {Calendar calendar AR = Calendar ar. getInstance (); calendar. set (Calendar. HOUR_OF_DAY, 11); calendar. set (Calendar. MINUTE, 39); calendar. set (Calendar. SECOND, 00); Date time = calendar. getTime (); return time;} public static void main (String [] args) {new TimerTest02 () ;}} public class TimerTaskTest02 extends TimerTask {@ Override public void run () {System. out. println ("specifies the time to execute the thread task... ");}}When the time reaches 11:39:00, the thread task will be executed. Of course, the task will be executed later than the time !! The execution result is:
Specify time = Tue Jun 10 11:39:00 CST 2014 specify time to execute a thread task...
2.3 After a specified delay, the scheduled task is executed cyclically at a specified interval.Public class TimerTest03 {Timer timer; public TimerTest03 () {timer = new Timer (); timer. schedule (new TimerTaskTest03 (), 1000,200 0);} public static void main (String [] args) {new TimerTest03 ();}} public class TimerTaskTest03 extends TimerTask {@ Override public void run () {Date date = new Date (this. scheduledExecutionTime (); System. out. println ("the execution time of this thread is:" + date );}}Running result:
The time for executing this thread is Tue Jun 10 21:19:47 CST 2014 the time for executing this thread is Tue Jun 10 21:19:49 CST 2014 the time for executing this thread is: tue Jun 10 21:19:51 CST 2014 the time for executing this thread is: Tue Jun 10 21:19:53 CST 2014 the time for executing this thread is: tue Jun 10 21:19:55 CST 2014 the time for executing this thread is: Tue Jun 10 21:19:57 CST 2014 .................
For this thread task, if we do not stop the task, it will continue to run.
For the above three instances, LZ is just a simple demonstration and does not explain the example of the scheduleAtFixedRate method. In fact, this method is the same as the schedule method!
2.4 analyze schedule and scheduleAtFixedRate1. schedule (TimerTask task, Date time), schedule (TimerTask task, long delay)
For the two methods, if the specified scheduled execution time scheduledExecutionTime <= systemCurrentTime, the task is executed immediately. ScheduledExecutionTime will not change because of the excessive execution of a task.
2. schedule (TimerTask task, Date firstTime, long period), schedule (TimerTask task, long delay, long period)
These two methods are a little different from the above two. The Timer task mentioned above will be delayed because of the long execution time of the previous task. In the two methods, the scheduled time of each executed task changes with the actual time of the previous task, that is, scheduledExecutionTime (n + 1) = realExecutionTime (n) + periodTime. That is to say, if the nth task causes this execution time process due to certain conditions, and finally causes systemCurrentTime> = scheduledExecutionTime (n + 1 ), this is the n + 1 task and will not be executed because of the time. It will wait until the n tasks are executed, this will inevitably lead to a change in the execution implementation scheduledExecutionTime of n + two, namely scheduledExecutionTime (n + 2) = realExecutionTime (n + 1) + periodTime. Therefore, these two methods focus more on the stability of the storage interval.
3. scheduleAtFixedRate (TimerTask task, Date firstTime, long period), scheduleAtFixedRate (TimerTask task, long delay, long period)
As mentioned above, the scheduleAtFixedRate and schedule methods have different focuses. The schedule method focuses on the stability of the storage interval, while the scheduleAtFixedRate method focuses more on maintaining the stability of the execution frequency. The reason is as follows. In the schedule method, the delay of the previous task will lead to the delay of the subsequent scheduled task, but the scheduleAtFixedRate method does not, if the execution time of the nth task is too long, causing systemCurrentTime> = scheduledExecutionTime (n + 1), no waiting task will be executed immediately, therefore, the execution time of the scheduleAtFixedRate method is different from that of schedule, but scheduledExecutionTime (n) = firstExecuteTime + n * periodTime. This calculation method will never change. Therefore, scheduleAtFixedRate is more focused on maintaining a stable execution frequency.
Iii. Defects of Timer 3.1 and TimerTimer timers can be scheduled (task execution at a specified time), delayed (task execution with a latency of 5 seconds), and periodically executed (tasks are executed every one second). However, Timer has some defects. First, Timer's support for scheduling is based on absolute time, rather than relative time, so it is very sensitive to system time changes. Second, the Timer thread will not capture exceptions. If the TimerTask throws an unchecked exception, the Timer thread will be terminated, and the Timer will not resume thread execution, he will mistakenly think that the entire Timer thread will be canceled. At the same time, timertasks that have not yet been executed by the scheduled ticket will not be executed, and new tasks cannot be scheduled. Therefore, if TimerTask throws an unchecked exception, Timer will generate unpredictable behavior.
1. Timer management time delay Defect
Previously, Timer only creates one thread task when executing a scheduled task. If there are multiple threads, if one of the threads causes the thread task to take a long time, when the interval between two tasks is exceeded, some defects may occur:
Public class TimerTest04 {private Timer timer; public long start; public TimerTest04 () {this. timer = new Timer (); start = System. currentTimeMillis ();} public void timerOne () {timer. schedule (new TimerTask () {public void run () {System. out. println ("timerOne invoked, the time:" + (System. currentTimeMillis ()-start); try {Thread. sleep (4000); // sleep thread 3000} catch (InterruptedException e) {e. printStackTrace () ;}}, 1000);} public void timerTwo () {timer. schedule (new TimerTask () {public void run () {System. out. println ("timerOne invoked, the time:" + (System. currentTimeMillis ()-start); }}, 3000);} public static void main (String [] args) throws Exception {TimerTest04 test = new TimerTest04 (); test. timerOne (); test. timerTwo ();}}According to our normal idea, timerTwo should be executed 3 seconds later, and the result should be:
timerOne invoked ,the time:1001timerOne invoked ,the time:3001
In contrast, timerOne sleep (4000) for 4 S and Timer is a thread internally, causing timeOne to take longer than the interval. Result:
timerOne invoked ,the time:1000timerOne invoked ,the time:5000
2. Timer throws an exception Defect
If TimerTask throws RuntimeException, Timer terminates all tasks. As follows:
Public class TimerTest04 {private Timer timer; public TimerTest04 () {this. timer = new Timer ();} public void timerOne () {timer. schedule (new TimerTask () {public void run () {throw new RuntimeException () ;}, 1000) ;}public void timerTwo () {timer. schedule (new TimerTask () {public void run () {System. out. println ("Will I execute ?? ") ;}}, 1000) ;}public static void main (String [] args) {TimerTest04 test = new TimerTest04 (); test. timerOne (); test. timerTwo ();}}Running result: timerOne throws an exception, causing timerTwo task to terminate.
Exception in thread "Timer-0" java.lang.RuntimeException at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505)
We can consider ScheduledThreadPoolExecutor to replace Timer defects. Timer is based on absolute time and sensitive to system time, while ScheduledThreadPoolExecutor is based on relative time. Timer is a single internal thread, while ScheduledThreadPoolExecutor is a thread pool, therefore, it supports concurrent execution of multiple tasks.
3.2 replace Timer with ScheduledExecutorService1. solution 1:
public class ScheduledExecutorTest { private ScheduledExecutorService scheduExec; public long start; ScheduledExecutorTest(){ this.scheduExec = Executors.newScheduledThreadPool(2); this.start = System.currentTimeMillis(); } public void timerOne(){ scheduExec.schedule(new Runnable() { public void run() { System.out.println("timerOne,the time:" + (System.currentTimeMillis() - start)); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } },1000,TimeUnit.MILLISECONDS); } public void timerTwo(){ scheduExec.schedule(new Runnable() { public void run() { System.out.println("timerTwo,the time:" + (System.currentTimeMillis() - start)); } },2000,TimeUnit.MILLISECONDS); } public static void main(String[] args) { ScheduledExecutorTest test = new ScheduledExecutorTest(); test.timerOne(); test.timerTwo(); }}Running result:
timerOne,the time:1003timerTwo,the time:2005
2. Problem 2
public class ScheduledExecutorTest { private ScheduledExecutorService scheduExec; public long start; ScheduledExecutorTest(){ this.scheduExec = Executors.newScheduledThreadPool(2); this.start = System.currentTimeMillis(); } public void timerOne(){ scheduExec.schedule(new Runnable() { public void run() { throw new RuntimeException(); } },1000,TimeUnit.MILLISECONDS); } public void timerTwo(){ scheduExec.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("timerTwo invoked ....."); } },2000,500,TimeUnit.MILLISECONDS); } public static void main(String[] args) { ScheduledExecutorTest test = new ScheduledExecutorTest(); test.timerOne(); test.timerTwo(); }}Running result:
timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .....timerTwo invoked .............................
References: http://blog.csdn.net/lmj623565791/article/details/27109467