Scheduledthreadpoolexecutor is a subclass of Threadpoolexecutor;
That's what the JDK API says:
ThreadPoolExecutor, it can schedule a command to run after a given delay, or execute a command on a regular basis. This class is preferable when multiple worker threads are required, or ThreadPoolExecutor when additional flexibility or functionality is required Timer .
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.
---------------
Usually we perform a timed task, will use time, and timetask to combine processing;
But there are some drawbacks to timer and TimerTask:
1:timer only one thread was created. When your task executes more than the set delay time will cause some problems.
The thread created by 2:timer does not handle the exception, so once a non-inspected exception is thrown, the thread terminates immediately.
It is recommended to use Scheduledthreadpoolexecutor after JDK 5.0. This class belongs to the executor Framework, which, in addition to handling exceptions, can create multiple threads to resolve the above problem
1 Packagetimer;2 3 ImportJava.text.SimpleDateFormat;4 Importjava.util.Date;5 ImportJava.util.concurrent.ScheduledThreadPoolExecutor;6 ImportJava.util.concurrent.TimeUnit;7 8 Public classTest9 {Ten StaticScheduledthreadpoolexecutor STP =NULL; One Static intindex; A - Private StaticString gettimes () { -SimpleDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss E"); theDate Date =NewDate (); - Date.settime (System.currenttimemillis ()); - returnFormat.format (date); - } + - + Private Static classMyTaskImplementsRunnable { A at @Override - Public voidrun () { -index++; -System.out.println ("2=" + gettimes () + "" +index); - //if (index >=10) { - //Stp.shutdown (); in //if (Stp.isshutdown ()) { - //System.out.println ("Stop???? "); to // } + // } - } the } * Public Static voidMain (string[] args) $ {Panax NotoginsengSTP =NewScheduledthreadpoolexecutor (5); -MyTask MyTask =NewMyTask (); the //MyTask is a thread, 2 is the first execution delay time, and the last parameter is the time unit + //Stp.schedule (MyTask, 2, timeunit.seconds); A //the first execution is delayed by 2 seconds, followed by a 1-second execution period the //stp.scheduleatfixedrate (MyTask, 2, 1,timeunit.seconds); + //first execution is delayed by 2 seconds, then 1 seconds from the last task end to the start of the next task -Stp.schedulewithfixeddelay (MyTask, 2, 1, timeunit.seconds); $ $ } - -}
Use Java-brought timer tasks Scheduledthreadpoolexecutor