Abstract: This article briefly introduces the difference between the Scheduled Thread Pool Executor class and the Timer class. Compared with the Timer class, what are the advantages of the Scheduled Thread Pool Executor class, and a simple example of the two implementations of task scheduling.
This article is shared from Huawei Cloud Community "[High Concurrency] Difference between ScheduledThreadPoolExecutor and Timer and Simple Examples" , author: Binghe.
JDK 1.5 began to provide the Scheduled Thread Pool Executor class. The Scheduled Thread Pool Executor class inherits the Thread Pool Executor class and reuses the thread pool to implement the periodic scheduling function of tasks. Before JDK 1.5, the periodic scheduling of tasks mainly used the Timer class and the Timer Task class. This article briefly introduces the difference between the Scheduled Thread Pool Executor class and the Timer class. Compared with the Timer class, what are the advantages of the Scheduled Thread Pool Executor class, and simple examples of the two implementations of task scheduling.
The difference between the two
Thread perspective
- Timer is a single-threaded mode. If the execution time of a TimerTask task is relatively long, it will affect the scheduled execution of other tasks.
- Scheduled Thread Pool Executor is a multi-threaded mode and reuses the thread pool. A Scheduled Future Task task takes a long time to execute and will not affect the scheduled execution of other tasks.
System time sensitivity
- Timer scheduling is based on the absolute time of the operating system and is sensitive to the time of the operating system. Once the time of the operating system changes, the scheduling of the Timer is no longer accurate.
- Scheduled Thread Pool Executor scheduling is based on relative time and is not affected by changes in operating system time.
Whether to catch the exception
- Timer will not catch exceptions thrown by Timer Task, and Timer is single-threaded. Once a certain scheduling task is abnormal, the entire thread will be terminated, and other tasks that need to be scheduled will no longer be executed.
- Scheduled Thread Pool Executor implements the scheduling function based on the thread pool. After a task throws an exception, other tasks can still be executed normally.
Whether the task has priority
- The Timer Task task executed in Timer has no concept of priority as a whole, but executes the task according to the absolute time of the system.
- The Scheduled Future Task class executed in the Scheduled Thread Pool Executor implements the java.lang.Comparable interface and the java.util.concurrent.Delayed interface, which also shows that the Scheduled Future Task class implements two very important methods, one is The compare To method of the java.lang.Comparable interface is the get Delay method of the java.util.concurrent.Delayed interface. The compare To method in the Scheduled Future Task class implements task comparison. Tasks with a short time interval from the next execution will be ranked first, that is, tasks with a short time interval from the next execution have a higher priority. The get Delay method can return the time interval from the next task execution.
Whether to support sorting tasks
- Timer does not support the sorting of tasks.
- A static internal class Delayed Work Queue is defined in the Scheduled Thread Pool Executor class. The Delayed Work Queue class is essentially an ordered queue. Each task that needs to be scheduled is sorted according to the size of the interval from the next execution.
Can you get the returned result
- The Timer Task class executed in Timer only implements the java.lang.Runnable interface, and cannot get the returned result from the Timer Task.
- The Scheduled Future Task class executed in the Scheduled Thread Pool Executor inherits the Future Task class and can obtain the returned result through Future.
Through the above analysis and comparison of the Scheduled Thread Pool Executor class and the Timer class, I believe that after JDK 1.5, there is no need to use Timer to implement scheduled task scheduling.
Simple example of both
Here, a simple example of using Timer and Scheduled Thread Pool Executor to implement timing scheduling is given. For simplicity, I will directly submit tasks in the form of anonymous internal classes.
Simple example of Timer class
The source code example is shown below.
package io.binghe.concurrent.lab09;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author binghe
* @version 1.0.0
* @description 测试Timer
*/
public class TimerTest {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("测试Timer类");
}
}, 1000, 1000);
Thread.sleep(10000);
timer.cancel();
}
}
The result of the operation is shown below.
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
测试Timer类
Simple example of Scheduled Thread Pool Executor class
The source code example is shown below.
package io.binghe.concurrent.lab09;
import java.util.concurrent.*;
/**
* @author binghe
* @version 1.0.0
* @description 测试ScheduledThreadPoolExecutor
*/
public class ScheduledThreadPoolExecutorTest {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("测试测试ScheduledThreadPoolExecutor");
}
}, 1, 1, TimeUnit.SECONDS);
//主线程休眠10秒
Thread.sleep(10000);
System.out.println("正在关闭线程池...");
// 关闭线程池
scheduledExecutorService.shutdown();
boolean isClosed;
// 等待线程池终止
do {
isClosed = scheduledExecutorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("正在等待线程池中的任务执行完成");
} while(!isClosed);
System.out.println("所有线程执行结束,线程池关闭");
}
}
The result of the operation is shown below.
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
测试测试ScheduledThreadPoolExecutor
正在关闭线程池...
测试测试ScheduledThreadPoolExecutor
正在等待线程池中的任务执行完成
所有线程执行结束,线程池关闭
Note: There are other usage methods for Timer and Scheduled Thread Pool Executor. Here, I will briefly list the above two usage examples. You can implement more usage methods by yourself.
Click to follow and learn about Huawei Cloud's fresh technology for the first time~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。