Java Multithreading Basics (ii) Timer class: Timer class and TimerTask class
The Timer class and the TimerTask class are an early way for the JDK to implement the timer function, and jdk1.5 previously supported the timer class and the TimerTask class. A new mechanism was introduced after JDK1.5, which will be studied in subsequent blog post.
1 perform a task after a specified time interval
ImportJava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public class traditionaltimertest { Public Static void Main(string[] args) {//Start the timer thread and execute the Run method of the TimerTask instance after 10000 milliseconds NewTimer (). Schedule (NewTimerTask () {@Override Public void Run() {System.out.println ("bombing!"); } },10000); while(true) {System.out.println ("clock time:"+NewDate (). getseconds ());Try{Thread.Sleep ( +);//main thread every 1 seconds, print current clock time}Catch(Interruptedexception e) {E.printstacktrace (); } } }}
The source code of the main Java API called and the Java doc:
public void schedule (timertask task, Long delay) {if (Delay < 0 ) throw new IllegalArgumentException ( "negative delay." ); Sched (Task, System.currenttimemillis () +delay, 0 ); }
Schedules the specified task for execution after the specified delay.
Schedules the specified task to execute after a specified delay.
Parameters:
Task-task to be scheduled.
Delay-delay in milliseconds before task was to be executed.
Throws:
Illegalargumentexception-if delay is a negative, or delay + system.currenttimemillis () is negative.
Illegalstateexception-if task is already scheduled or cancelled, timer was cancelled, or timer thread terminated.
Nullpointerexception-if task is null
2 recurring tasks After a specified time interval
ImportJava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public class traditionaltimertest { Public Static void Main(string[] args) {//Start the timer thread and start at 10000 milliseconds and perform a scheduled task every 3000 milliseconds NewTimer (). Schedule (NewTimerTask () {//Timed Tasks @Override Public void Run() {System.out.println ("bombing!"); } },10000, the); while(true) {System.out.println ("clock time:"+NewDate (). getseconds ());Try{Thread.Sleep ( +);//main thread every 1 seconds, print current clock time}Catch(Interruptedexception e) {E.printstacktrace (); } } }}
The source code of the main Java API called and the Java doc:
publicvoidschedulelonglong period) { if0) thrownew IllegalArgumentException("Negative delay."); if0) thrownew IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); }
Schedules the specified task for repeated fixed-delay execution and beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
Schedules the specified task to start repeating fixed deferred execution from the specified delay. Follow-up is performed at approximately fixed intervals (delimited by the specified period).
In Fixed-delay execution, each execution was scheduled relative to the actual execution time of the previous execution. If an execution are delayed for any reason (such as garbage collection or other background activity), subsequent executions would be delayed as well. In the long run, the frequency of execution would generally be slightly lower than the reciprocal of the specified period ( Assuming the system clock underlying object.wait (long) is accurate).
In a fixed deferred execution, each execution is scheduled based on the actual execution time of the previous execution. If an execution is delayed for any reason, such as a garbage collection or other background activity, subsequent executions will also be deferred. In the long run, the frequency of execution is generally slightly slower than the reciprocal of the specified period (assuming that the system clock relied on by object.wait (long) is accurate).
Fixed-delay execution is appropriate for recurring activities, require "smoothness." In other words, it's appropriate for activities where it's more important to keep the frequency accurate in the short RU n than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed on response to human input, such as automatically repeating a Character as long as a key is held down.
Fixed-delay execution applies to repetitive activities that require "smooth" running. In other words, it is suitable for activities that are more accurate in the short run than those that are more important in the long run. This includes most animation tasks, such as the blinking cursor at fixed intervals. This also includes fixed activities that are performed to respond to human-machine input, such as automatically repeating input characters when the key is pressed.
Parameters:
Task-task to be scheduled.
Delay-delay in milliseconds before task was to be executed.
Period-time in milliseconds between successive task executions.
Throws:
Illegalargumentexception-if Delay < 0, or delay + system.currenttimemillis () < 0, or period <= 0
Illegalstateexception-if task is already scheduled or cancelled, timer was cancelled, or timer thread terminated.
Nullpointerexception-if task is null
3 more flexibility in spacing
Every 2 seconds, 4 seconds, 2 seconds, 4 seconds, ..., the loop executes the task.
Method 1 defines a TimerTask class
ImportJava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public class traditionaltimertest { Static intCount =0; Public Static void Main(string[] args) {Class Mytimertask extends TimerTask {@Override Public void Run() {count = (count+1)%2;//Used to customize the different time intervalsSystem.out.println ("bombing!");NewTimer (). Schedule (NewMytimertask (),//Recursively instantiate a new scheduled task -+ -* count); } }NewTimer (). Schedule (NewMytimertask (), -); while(true) {System.out.println ("clock time:"+NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {E.printstacktrace (); } } }}
Method 2 defines two/more TimerTask classes
ImportJava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public class traditionaltimertest { Public Static void Main(string[] args) {NewTimer (). Schedule (NewMyTimerTask1 (), -); while(true) {System.out.println ("clock time:"+NewDate (). getseconds ());Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {E.printstacktrace (); }}}}class MyTimerTask1 extends TimerTask {@Override Public void Run() {System.out.println ("Task1");NewTimer (). Schedule (NewMyTimerTask2 (), -);//Start a scheduled Task 2}}class MyTimerTask2 extends TimerTask {@Override Public void Run() {System.out.println ("Task2");NewTimer (). Schedule (NewMyTimerTask1 (),4000);//Start a scheduled Task 1}}
4 other common APIs for timer
return value |
method Signature |
void |
Schedule (timertask task, Date time) Schedules the specified task for execution at the specified time. Schedules the specified task to execute at the specified time. If this time has passed, schedule the task to execute immediately. |
void |
Schedule (timertask task, Date Firsttime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Schedules the specified task to begin repeating fixed deferred execution at a specified time. Follow-up is performed at approximately fixed intervals (delimited by the specified period).
In a fixed deferred execution, each execution is scheduled based on the actual execution time of the previous execution. If an execution is delayed for any reason, such as a garbage collection or other background activity, subsequent executions will also be deferred . In the long run, the frequency of execution is generally slightly slower than the reciprocal of the specified period (assuming that the system clock relied on by object.wait (long) is accurate).
Fixed deferred execution is for repetitive execution activities that require "smooth" running. In other words, it is suitable for activities that are more accurate in the short run than those that are more important in the long run. This includes most animation tasks, such as the blinking cursor at fixed intervals. This also includes fixed activities that are performed in response to human activity, such as automatically repeating the input characters while holding down the key. |
void |
Schedule (timertask task, long delay) Schedules the specified task for execution after the specified delay. Schedules the specified task to execute after a specified delay. |
void |
Schedule (timertask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution and beginning after the specified delay. Schedules the specified task to start repeating fixed deferred execution from the specified delay. Follow-up is performed at approximately fixed intervals (delimited by the specified period).
In a fixed deferred execution, each execution is scheduled based on the actual execution time of the previous execution. If an execution is delayed for any reason, such as a garbage collection or other background activity, subsequent executions will also be deferred . In the long run, the frequency of execution is generally slightly slower than the reciprocal of the specified period (assuming that the system clock relied on by object.wait (long) is accurate).
Fixed-delay execution applies to repetitive activities that require "smooth" running. In other words, it is suitable for activities that are more accurate in the short run than those that are more important in the long run. This includes most animation tasks, such as the blinking cursor at fixed intervals. This also includes fixed activities that are performed in response to human activity, such as automatically repeating the input characters while holding down the key. |
void |
scheduleatfixedrate (timertask task, Date Firsttime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. The schedules the specified task to start at a specified time at a recurring fixed rate of execution. Follow-up is performed at approximately fixed intervals (delimited by the specified period). Schedules Each execution in a fixed rate execution, relative to the scheduled initial execution time. If an execution is delayed for any reason, such as a garbage collection or other background activity, it will occur two or more times in a quick succession, so that subsequent execution can catch up . In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming that the system clock relied on by object.wait (long) is accurate). Fixed rate execution applies to repetitive execution activities that are time-sensitive, such as hourly timekeeping, or running scheduled maintenance activities at a specific time of day. It also applies to repetitive activities that are important for the total time to complete a fixed number of executions, such as a countdown timer that ticks once every second for 10 seconds. Finally, the fixed rate execution applies to timer tasks that schedule repeated executions, which must be synchronized with each other. |
void |
Scheduleatfixedrate (timertask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution and beginning after the specified delay. Schedules the specified task to begin repeating a fixed rate of execution after a specified delay. Follow-up is performed at approximately fixed intervals (delimited by the specified period).
In a fixed rate execution, each execution is scheduled according to the scheduled initial execution time. If an execution is delayed for any reason, such as a garbage collection or other background activity, two or more executions will occur quickly and continuously, allowing subsequent executions to "catch up". In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming that the system clock relied on by object.wait (long) is accurate).
Fixed rate execution applies to repetitive execution activities that are sensitive to absolute time, such as hourly timekeeping, or running scheduled maintenance activities at specific times of the day. It also applies to repetitive activities that are important for the total time to complete a fixed number of executions, such as a countdown timer that ticks once every second for 10 seconds. Finally, fixed rate execution is appropriate for scheduling multiple recurring timer tasks that must be synchronized with each other. |
For more detailed API information, refer to the Java SE API:
English api:http://docs.oracle.com/javase/6/docs/api/index.html
Chinese Api:http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
More complex timers can use the Quartz library: http://www.quartz-scheduler.org/
Java Multithreading Basics (ii) Timer class: Timer class and TimerTask class