Task Scheduling (4) -- ScheduledExecutorService replaces Timer to implement multi-thread task scheduling and scheduledexecutor
In the previous blog, Task Scheduling (III)-Introduction to ScheduledExecutorService, a substitute for Timer, has introduced ScheduledExecutorService briefly. In fact, it is imperative to use ScheduledExecutorService to replace Timer. The main reasons are as follows:
The first problem is that with the surge in business data, it takes 1-3 hours to execute several tasks in production. During this period, other tasks under the timer can only wait, this is intolerable. Reopen a Timer? Isn't it possible to open a single Timer for all time-consuming tasks? This is too messy.
The second problem is extremely fatal. A lot of business data is run by scheduled tasks at night. As a result, the thread is killed due to program problems or insufficient memory resources. All the tasks under the timer are not executed. As a result, the job is busy for one day the next day. The main task is to run the task and adjust the data. It has suffered a lot!
To make up for the defects of Timer, the ScheduledExecutorService provided in jdk1.5 is introduced and sent. The implementation class is ScheduledThreadPoolExecutor. ScheduledThreadPoolExecutor supports multithreading and captures exceptions in the thread. Therefore, it is the perfect replacement for Timer.
Share an instance:
/*** Task2 * @ author arron * @ date 2:08:34 on January 1, August 5, 2015 * @ version 1.0 */public class Task2 extends TimerTask {@ SuppressWarnings ("deprecation") @ Overridepublic void run () {System. out. println ("---- task2 start --------" + new Date (). toLocaleString (); try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("---- 5 s later, task2 end --------" + new Date (). toLocaleString ());}}
Test code:
Public static void main (String [] args) {ScheduledExecutorService pool = Executors. newScheduledThreadPool (2); // enable two threads, Task1 t1 = new Task1 (); // run immediately. The task consumes 3 seconds. Wait 2 seconds after the execution ends, [When there is a spare thread], run the task pool again. scheduleWithFixedDelay (t1, 0, 2, TimeUnit. SECONDS); // run the task immediately. The task consumes 5 SECONDS. Wait 2 SECONDS after execution. [when there is a spare thread], run the task Task2 t2 = new Task2 () again (); pool. scheduleWithFixedDelay (t2, 0, 2, TimeUnit. SECONDS );}
Execution result
In this way, tasks will not affect each other and can be executed simultaneously. But set the number of threads. It is also counterproductive to increase the number of threads in the transition.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.