Tag: exe initial override task is greater than OID invoke service cut
Java Timer Task Timer
1. When performing multiple tasks, the second must be executed before the first one executes.
2, the timer is single-threaded execution, so a task thrown exception, other tasks can not be executed.
Import Java.util.Timer; Import Java.util.TimerTask; public class Timertest {private static long start; public static void Main (string[] args) throws Exception {TimerTask Task1 = new TimerTask () { @Override public void Run () {System.out.println (' Task1 in Voked! "+ (System.currenttimemillis ()-start)); try {thread.sleep (3000); } catch (Interruptedexception e) {e.printstacktrace (); } } }; TimerTask task2 = new TimerTask () {@Override public void run () { System.out.println ("Task2 invoked!") + (System.currenttimemillis ()-start)); } }; Timer timeR = new Timer (); Start = System.currenttimemillis (); Timer.schedule (Task1, 1000); Timer.schedule (TASK2, 3000); } }
Execution Result:
Task1 invoked! 1000
Task2 invoked! 4000
Newscheduledthreadpool:
1. Multiple threads can perform different tasks at the same time.
2, because it is a number of threads all, the task throws an exception, does not affect the execution of other tasks.
- After scheduleatfixedrate:0s, start the task, the start time of the previous task and the start time of the next task is 5s, if the previous task execution time is greater than 5s, then the next task will wait in the queue until the previous task has finished executing.
After the schedulewithfixeddelay:0s begins to perform the task, the end time of the previous task and the start time of the next task are 5s.
public class Scheduled {static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);static class Task implements Runnable { public void run() { try { Thread.sleep(2000L); System.out.println(Thread.currentThread().getName()); } catch (Exception e) { } }}/** * command:执行线程 * initialDelay:初始化延时 * period:两次开始执行最小间隔时间 * delay:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间) * unit:计时单位 */public static void main(String[] args) { scheduledExecutorService.scheduleAtFixedRate(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS); scheduledExecutorService.scheduleWithFixedDelay(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);}}
Timer and Scheduledexecutorservice for Java timer tasks