4. Use of timer and timer tasks
Timer is a timer tool used to plan to execute specified tasks in a background thread. These tasks can be executed once or regularly. Each timer object corresponds to a background thread that executes all timer tasks sequentially. If it takes too long to complete a timer task, it will "exclusively" the task execution thread of the timer, which may delay subsequent task execution. After the final reference of the timer object is completed and all unprocessed tasks have been executed, the timer task execution thread will terminate normally (and become the garbage collection object ). Timertask is an abstract class that implements the runable interface. Its subclass represents a task that can be scheduled by timer.
1) A simple demo that gives you a perceptual knowledge of the use of timer and timertask.
2) Description of common API functions of timer and timertask
The difference between schedule and scheduleatfixedrate of the Timer class is emphasized here. The difference between schedule and scheduleatfixedrate is that schedule is executed at a fixed interval of time. If an execution is delayed, the execution time of subsequent execution will also be delayed; scheduleatfixedrate is executed at an absolute interval. If an execution is delayed, the latency of the last execution will be shortened (scheduleatfixedrate also takes the past time as a periodic execution ). Schedule focuses on the Stability of time intervals, while scheduleatfixedrate focuses on the Stability of execution frequency.
3) Termination of Timer
By default, as long as the timer thread of a program is running, the program will remain running. Of course, you can terminate a timer thread in the following four ways:
A) call the timer cancle method. You can call this method from anywhere in the program, even in the run method of a timer task;
B) Let the timer thread become a daemon thread (you can use new timer (true) to achieve this goal when creating the timer), so that when the program only has the daemon thread, it will automatically terminate the operation;
C) After all tasks related to the timer are executed, the timer thread will also terminate when all references to the timer object are deleted (set to null;
D) Call the system. Exit method to terminate the entire program (All threads.
Conclusion: timer and timertask can be simply understood as the timer is used to trigger the timertask call. The schedule and scheduleatfixedrate methods are usually used to call the timertask and cancle is used to terminate the task call. Timer is easy to use and is suitable for providing lightweight timer functions. However, you can use other methods to schedule highly time-sensitive tasks (as described in javadoc, "timer does not offer real-time guarantees: it schedules tasks using the object. wait (long) method ").
Address: http://shuaihong.blog.chinabyte.com/2010/03/24/33/