Reprinted from http://janeky.iteye.com/blog/770441
----------------------------------------------------------------------------------
6. Scheduledthreadpoolexecutor
Let's start by learning more about this class in the JDK1.5 API:
"You can schedule a command to run after a given delay, or execute a command on a regular basis." This class is better than a Timer when multiple worker threads are required, or if threadpoolexecutor is required to have additional flexibility or functionality.
Once the deferred task is enabled, it is executed, but there is no real-time guarantee as to when it is enabled and when it is executed. Enable tasks that are scheduled for the same execution time, in the first In, Out (FIFO) order that is submitted.
Although this class inherits from Threadpoolexecutor, several inherited tuning methods have no effect on this class. In particular, because it is a fixed-size pool that uses corepoolsize threads and a unbounded queue, adjusting maximumpoolsize has little effect. "
Prior to JDK1.5, we implemented timer/cycle operations through timers. But the timer has several dangers [JCIP]
The A.timer is based on absolute time. Easily affected by the system clock.
B.timer only creates a new thread to perform all the timetask. All timetask may have a related impact
C.timer does not catch timertask exceptions, but simply stops them. This will inevitably affect the execution of other timetask.
If you are using JDK1.5 or above, it is recommended to replace the timer with Scheduledthreadpoolexecutor. It basically solves the above problem. It uses the relative time, uses the thread pool to execute TimerTask, will come out TimerTask exception.
The following is a simple example to illustrate the use of scheduledthreadpoolexecutor.
We regularly throw the timer out of the ordinary
We regularly print system time from the console
The code is as follows (refer to some of the code on the Internet, here to express our thanks)
Java code
- Import Java.util.concurrent.ScheduledThreadPoolExecutor;
- Import Java.util.concurrent.TimeUnit;
- Public class Testscheduledthreadpoolexecutor {
- public static void Main (string[] args) {
- Scheduledthreadpoolexecutor exec=New Scheduledthreadpoolexecutor (1);
- Exec.scheduleatfixedrate (new Runnable () {//each time an exception is triggered
- @Override
- public Void Run () {
- throw new RuntimeException ();
- }}, +, timeunit.milliseconds);
- Exec.scheduleatfixedrate (new Runnable () {//print the system time every once in a while to prove that the two do not affect each other
- @Override
- public Void Run () {
- System.out.println (System.nanotime ());
- }}, +, timeunit.milliseconds);
- }
- }
Summary: It's time to change your timer to Scheduledthreadpoolexecutor.
[Reprint] Java multithreaded learning-java.util.concurrent (iii) Scheduledthreadpoolexecutor