Executors.newScheduledThreadPool
實際返回類型:
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @param threadFactory the factory to use when the executor
* creates a new thread
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
* @throws NullPointerException if threadFactory is null
*/
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
實例
scheduleAtFixedRate
方法:
-
initialDelay
設置方法第一次執行前的延時時間, 設置為0
即馬上就執行. -
period
用于控制后續的重復執行.
該方法的計時從前一次執行的開始
計時. 比如說第一次執行是在第1
秒,period
為1
秒, 那么第二次執行將會在第2
秒開始, 第3
次執行將會在第3
秒開始... 如果出現某次任務的執行時長超過period
, 那么需要等待這次執行完成才會開始下一次.
即該方法的下一次執行時間為max(上一次執行需要花的時間, period)
. - 如果某次執行過程中拋出了
exception
, 那么后續的執行將不會再繼續了.
/**
* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the given
* period; that is executions will commence after
* {@code initialDelay} then {@code initialDelay+period}, then
* {@code initialDelay + 2 * period}, and so on.
* If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor. If any execution of this task
* takes longer than its period, then subsequent executions
* may start late, but will not concurrently execute.
*
* @param command the task to execute
* @param initialDelay the time to delay first execution
* @param period the period between successive executions
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of
* the task, and whose {@code get()} method will throw an
* exception upon cancellation
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
* @throws IllegalArgumentException if period less than or equal to zero
*/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
實例:
public static void testScheduleAtFixedRate(){
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("working at: " + getCurrentTime());
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
};
ScheduledFuture<?> future = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);
Thread main = Thread.currentThread();
scheduledExecutorService.schedule(()-> main.interrupt(), 5000, TimeUnit.MILLISECONDS);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
future.cancel(true);
}
}
輸出:
working at: 23:07:17
working at: 23:07:19
working at: 23:07:21
從輸出可以看出, 第一次執行開始于23:07:17
, 按照period
參數1000
, 第二次執行應該是在23:07:18
, 但是實際是在23:07:19
, 因為任務執行一次需要2000
毫秒, 所以即使period
計時滿足了, 仍然要等待前一次執行完成, 才會執行下一次.
scheduleWithFixedDelay
方法
注釋:
/**
* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the
* given delay between the termination of one execution and the
* commencement of the next. If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor.
*
* @param command the task to execute
* @param initialDelay the time to delay first execution
* @param delay the delay between the termination of one
* execution and the commencement of the next
* @param unit the time unit of the initialDelay and delay parameters
* @return a ScheduledFuture representing pending completion of
* the task, and whose {@code get()} method will throw an
* exception upon cancellation
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
* @throws IllegalArgumentException if delay less than or equal to zero
*/
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
與scheduleAtFixedRate
不同的是, scheduleWithFixedDelay
方法的delay
計時開始于上一次執行結束. 即下一次執行的時間為上一次執行完畢后再過delay
時間.
實例:
public static void testScheduleWithFixedDelay(){
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("working at: " + getCurrentTime());
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
};
ScheduledFuture<?> future = scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 2000, TimeUnit.MILLISECONDS);
Thread main = Thread.currentThread();
scheduledExecutorService.schedule(() -> main.interrupt(), 10, TimeUnit.SECONDS);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
future.cancel(true);
}
}
輸出:
working at: 23:12:07
working at: 23:12:11
working at: 23:12:15
可以看出下一次執行都是在上一次執行完畢后的2000
毫秒后 (注意一次執行花費2000
毫秒).