Most visited

Recently visited

Added in API level 1

ScheduledThreadPoolExecutor

public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor implements ScheduledExecutorService

java.lang.Object
   ↳ java.util.concurrent.AbstractExecutorService
     ↳ java.util.concurrent.ThreadPoolExecutor
       ↳ java.util.concurrent.ScheduledThreadPoolExecutor


一个ThreadPoolExecutor ,可以额外安排命令在给定延迟后运行,或定期执行。 该类优选的是Timer需要多个工作线程时,或当附加灵活性或能力ThreadPoolExecutor需要(这此类扩展)。

延迟任务在启用后立即执行,但在启用后,他们将开始执行任何实时保证。 按先进先出(FIFO)顺序启用预定完全相同执行时间的任务。

当提交的任务在运行之前被取消时,执行被取消。 默认情况下,这种取消的任务不会自动从工作队列中删除,直到延迟结束。 虽然这可以进行进一步的检查和监测,但也可能会导致取消任务的无限保留。

通过scheduleAtFixedRatescheduleWithFixedDelay计划的定期任务的连续执行不会重叠。 虽然不同的执行可以通过不同的线程来执行,先前执行的效果happen-before那些随后的那些的。

虽然此类继承自ThreadPoolExecutor ,但一些继承的调整方法对此并不有用。 特别是,因为它使用corePoolSize线程和无限队列作为固定大小的池,所以对maximumPoolSize调整没有任何效果。 此外,将corePoolSize设置为零或使用allowCoreThreadTimeOut几乎不是一个好主意,因为这可能使池无线程处理任务,一旦它们有资格运行。

扩展说明:该类重写executesubmit方法以生成内部ScheduledFuture对象,以控制每个任务的延迟和调度。 为了保留功能,子类中的这些方法的任何进一步重写都必须调用超类版本,这有效地禁用了额外的任务定制。 然而,此类提供替代保护扩展方法decorateTask (每一个用于一个版本RunnableCallable ),其可以被用于定制用于执行经由输入的命令的具体任务类型executesubmitschedulescheduleAtFixedRate ,和scheduleWithFixedDelay 默认情况下, ScheduledThreadPoolExecutor使用扩展FutureTask的任务类型。 但是,可以使用以下形式的子类对其进行修改或替换:

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Runnable r, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(r, task);
   }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Callable<V> c, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(c, task);
   }
   // ... add constructors, etc.
 }

Summary

Public constructors

ScheduledThreadPoolExecutor(int corePoolSize)

用给定的核心池大小创建一个新的 ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

Public methods

void execute(Runnable command)

以零所需延迟执行 command

boolean getContinueExistingPeriodicTasksAfterShutdownPolicy()

获取是否继续执行现有的周期性任务的策略,即使此执行程序为 shutdown

boolean getExecuteExistingDelayedTasksAfterShutdownPolicy()

获取是否执行现有的延迟任务的策略,即使此执行程序为 shutdown

BlockingQueue<Runnable> getQueue()

返回此执行程序使用的任务队列。

boolean getRemoveOnCancelPolicy()

获取是否应在取消时立即从工作队列中删除已取消的任务的策略。

<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)

创建并执行一个ScheduledFuture,在给定的延迟后变为启用状态。

ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)

创建并执行在给定延迟后变为启用的一次性操作。

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

创建并执行一个定期动作,在给定的初始延迟之后首先变为启用,然后在给定的时间段内启用; 也就是说,处决将在initialDelay之后开始,然后是initialDelay + period ,然后是initialDelay + 2 * period ,依此类推。

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

创建并执行一个定期动作,该动作在给定的初始延迟后首先变为有效,随后在一次执行终止和下一次执行终止之间给定延迟。

void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)

设置是否继续执行现有的周期性任务的策略,即使此执行程序为 shutdown

void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)

设置是否执行现有延迟任务的策略,即使此执行程序为 shutdown

void setRemoveOnCancelPolicy(boolean value)

设置是否取消时应立即从工作队列中删除已取消的任务的策略。

void shutdown()

启动先前提交的任务执行的有序关闭,但不会接受新任务。

List<Runnable> shutdownNow()

尝试停止所有正在执行的任务,暂停等待任务的处理,并返回正在等待执行的任务列表。

Future<?> submit(Runnable task)

提交可执行的任务并返回表示该任务的Future。

<T> Future<T> submit(Callable<T> task)

提交执行的返回值任务,并返回表示未完成任务结果的Future。

<T> Future<T> submit(Runnable task, T result)

提交可执行的任务并返回表示该任务的Future。

Protected methods

<V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task)

修改或替换用于执行可运行的任务。

<V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task)

修改或替换用于执行可调用任务的任务。

Inherited methods

From class java.util.concurrent.ThreadPoolExecutor
From class java.util.concurrent.AbstractExecutorService
From class java.lang.Object
From interface java.util.concurrent.ExecutorService
From interface java.util.concurrent.ScheduledExecutorService
From interface java.util.concurrent.Executor

Public constructors

ScheduledThreadPoolExecutor

Added in API level 1
ScheduledThreadPoolExecutor (int corePoolSize)

用给定的核心池大小创建一个新的 ScheduledThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
Throws
IllegalArgumentException if corePoolSize < 0

ScheduledThreadPoolExecutor

Added in API level 1
ScheduledThreadPoolExecutor (int corePoolSize, 
                ThreadFactory threadFactory)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
threadFactory ThreadFactory: the factory to use when the executor creates a new thread
Throws
IllegalArgumentException if corePoolSize < 0
NullPointerException if threadFactory is null

ScheduledThreadPoolExecutor

Added in API level 1
ScheduledThreadPoolExecutor (int corePoolSize, 
                RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
handler RejectedExecutionHandler: the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws
IllegalArgumentException if corePoolSize < 0
NullPointerException if handler is null

ScheduledThreadPoolExecutor

Added in API level 1
ScheduledThreadPoolExecutor (int corePoolSize, 
                ThreadFactory threadFactory, 
                RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ScheduledThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
threadFactory ThreadFactory: the factory to use when the executor creates a new thread
handler RejectedExecutionHandler: the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws
IllegalArgumentException if corePoolSize < 0
NullPointerException if threadFactory or handler is null

Public methods

execute

Added in API level 1
void execute (Runnable command)

执行command ,延迟时间为零。 这具有等效于schedule(command, 0, anyUnit)效果。 请注意,检查队列和由shutdownNow返回的列表将访问零延迟ScheduledFuture ,而不是command本身。

使用ScheduledFuture对象的afterExecute是始终使用空秒Throwable参数调用Throwable ,即使command突然终止。 相反,由这样的任务抛出的Throwable可以通过get()获得。

Parameters
command Runnable: the task to execute
Throws
RejectedExecutionException at discretion of RejectedExecutionHandler, if the task cannot be accepted for execution because the executor has been shut down
NullPointerException

getContinueExistingPeriodicTasksAfterShutdownPolicy

Added in API level 1
boolean getContinueExistingPeriodicTasksAfterShutdownPolicy ()

获取有关是否继续执行现有的周期性任务的策略,即使此执行程序为shutdown 在这种情况下,这些任务将仅在终止shutdownNow或策略设置后false时已关机。 该值默认为false

Returns
boolean true if will continue after shutdown

也可以看看:

getExecuteExistingDelayedTasksAfterShutdownPolicy

Added in API level 1
boolean getExecuteExistingDelayedTasksAfterShutdownPolicy ()

获取是否执行现有的延迟任务的策略,即使此执行程序为shutdown 在这种情况下,这些任务将仅在shutdownNow终止,或者在已经关闭时将策略设置为false后终止。 该值默认为true

Returns
boolean true if will execute after shutdown

也可以看看:

getQueue

Added in API level 1
BlockingQueue<Runnable> getQueue ()

返回此执行程序使用的任务队列。 访问任务队列主要用于调试和监视。 该队列可能处于活动状态。 检索任务队列不会阻止排队的任务执行。

这个队列的每个元素是一个ScheduledFuture 对于通过schedule方法之一提交的任务,该元素将与返回的ScheduledFuture相同。 对于使用execute提交的任务,该元素将为零延迟ScheduledFuture

不能保证对这个队列的迭代以它们将要执行的顺序遍历任务。

Returns
BlockingQueue<Runnable> the task queue

getRemoveOnCancelPolicy

Added in API level 21
boolean getRemoveOnCancelPolicy ()

获取是否应在取消时立即从工作队列中删除已取消的任务的策略。 该值默认为false

Returns
boolean true if cancelled tasks are immediately removed from the queue

也可以看看:

schedule

Added in API level 1
ScheduledFuture<V> schedule (Callable<V> callable, 
                long delay, 
                TimeUnit unit)

创建并执行一个ScheduledFuture,在给定的延迟后变为启用状态。

Parameters
callable Callable: the function to execute
delay long: the time from now to delay execution
unit TimeUnit: the time unit of the delay parameter
Returns
ScheduledFuture<V> a ScheduledFuture that can be used to extract result or cancel
Throws
RejectedExecutionException
NullPointerException

schedule

Added in API level 1
ScheduledFuture<?> schedule (Runnable command, 
                long delay, 
                TimeUnit unit)

创建并执行在给定延迟后变为启用的一次性操作。

Parameters
command Runnable: the task to execute
delay long: the time from now to delay execution
unit TimeUnit: the time unit of the delay parameter
Returns
ScheduledFuture<?> a ScheduledFuture representing pending completion of the task and whose get() method will return null upon completion
Throws
RejectedExecutionException
NullPointerException

scheduleAtFixedRate

Added in API level 1
ScheduledFuture<?> scheduleAtFixedRate (Runnable command, 
                long initialDelay, 
                long period, 
                TimeUnit unit)

创建并执行一个定期动作,在给定的初始延迟之后首先变为启用,然后在给定的时间段内启用; 也就是说,执行将在initialDelay之后开始,然后是initialDelay + period ,然后是initialDelay + 2 * period ,依此类推。

任务执行顺序无限期地继续,直到发生以下异常完成之一:

  • The task is explicitly cancelled via the returned future.
  • The executor terminates, also resulting in task cancellation.
  • An execution of the task throws an exception. In this case calling get on the returned future will throw ExecutionException.
Subsequent executions are suppressed. Subsequent calls to isDone() on the returned future will return true.

如果任务的执行时间比其周期长,则后续执行可能会晚点,但不会同时执行。

Parameters
command Runnable: the task to execute
initialDelay long: the time to delay first execution
period long: the period between successive executions
unit TimeUnit: the time unit of the initialDelay and period parameters
Returns
ScheduledFuture<?> a ScheduledFuture representing pending completion of the series of repeated tasks. The future's get() method will never return normally, and will throw an exception upon task cancellation or abnormal termination of a task execution.
Throws
RejectedExecutionException
NullPointerException
IllegalArgumentException

scheduleWithFixedDelay

Added in API level 1
ScheduledFuture<?> scheduleWithFixedDelay (Runnable command, 
                long initialDelay, 
                long delay, 
                TimeUnit unit)

创建并执行一个定期动作,该动作在给定的初始延迟后首先变为有效,随后在一次执行终止和下一次执行终止之间给定延迟。

任务执行顺序无限期地继续,直到发生以下异常完成之一:

  • The task is explicitly cancelled via the returned future.
  • The executor terminates, also resulting in task cancellation.
  • An execution of the task throws an exception. In this case calling get on the returned future will throw ExecutionException.
Subsequent executions are suppressed. Subsequent calls to isDone() on the returned future will return true.

Parameters
command Runnable: the task to execute
initialDelay long: the time to delay first execution
delay long: the delay between the termination of one execution and the commencement of the next
unit TimeUnit: the time unit of the initialDelay and delay parameters
Returns
ScheduledFuture<?> a ScheduledFuture representing pending completion of the series of repeated tasks. The future's get() method will never return normally, and will throw an exception upon task cancellation or abnormal termination of a task execution.
Throws
RejectedExecutionException
NullPointerException
IllegalArgumentException

setContinueExistingPeriodicTasksAfterShutdownPolicy

Added in API level 1
void setContinueExistingPeriodicTasksAfterShutdownPolicy (boolean value)

设置是否继续执行现有的周期性任务的策略,即使此执行程序为shutdown 在这种情况下,这些任务将仅在终止shutdownNow或策略设置后false时已关机。 该值默认为false

Parameters
value boolean: if true, continue after shutdown, else don't

也可以看看:

setExecuteExistingDelayedTasksAfterShutdownPolicy

Added in API level 1
void setExecuteExistingDelayedTasksAfterShutdownPolicy (boolean value)

设置是否执行现有的延迟任务的策略,即使此执行程序为shutdown 在这种情况下,这些任务将仅在shutdownNow终止,或者在已经关闭时将策略设置为false之后终止。 该值默认为true

Parameters
value boolean: if true, execute after shutdown, else don't

也可以看看:

setRemoveOnCancelPolicy

Added in API level 21
void setRemoveOnCancelPolicy (boolean value)

设置是否取消时应立即从工作队列中删除已取消的任务的策略。 该值默认为false

Parameters
value boolean: if true, remove on cancellation, else don't

也可以看看:

shutdown

Added in API level 1
void shutdown ()

启动先前提交的任务执行的有序关闭,但不会接受新任务。 如果已关闭,调用没有其他影响。

此方法不会等待先前提交的任务完成执行。 使用awaitTermination来做到这一点。

如果ExecuteExistingDelayedTasksAfterShutdownPolicy已设置为false ,则延迟尚未过去的现有延迟任务将被取消。 除非ContinueExistingPeriodicTasksAfterShutdownPolicy已被设置true ,否则未来执行现有的周期性任务将被取消。

shutdownNow

Added in API level 1
List<Runnable> shutdownNow ()

尝试停止所有正在执行的任务,暂停等待任务的处理,并返回正在等待执行的任务列表。 从此方法返回后,这些任务将从任务队列中排出(除去)。

此方法不会等待主动执行的任务终止。 使用awaitTermination来做到这一点。

除了竭尽全力尝试停止处理主动执行的任务之外,没有任何保证。 该实现通过interrupt()中断任务; 任何不能响应中断的任务可能永远不会终止。

Returns
List<Runnable> list of tasks that never commenced execution. Each element of this list is a ScheduledFuture. For tasks submitted via one of the schedule methods, the element will be identical to the returned ScheduledFuture. For tasks submitted using execute, the element will be a zero-delay ScheduledFuture.

submit

Added in API level 1
Future<?> submit (Runnable task)

提交可执行的任务并返回表示该任务的Future。 成功完成后,未来的get方法将返回null

Parameters
task Runnable: the task to submit
Returns
Future<?> a Future representing pending completion of the task
Throws
RejectedExecutionException
NullPointerException

submit

Added in API level 1
Future<T> submit (Callable<T> task)

提交执行的返回值任务,并返回表示未完成任务结果的Future。 未来的get方法将在成功完成后返回任务的结果。

如果您想立即阻止等待任务,可以使用表单 result = exec.submit(aCallable).get();

注意: Executors类包含一组方法,可以将一些其他常见闭包对象(例如, PrivilegedActionCallable表单,以便它们可以提交。

Parameters
task Callable: the task to submit
Returns
Future<T> a Future representing pending completion of the task
Throws
RejectedExecutionException
NullPointerException

submit

Added in API level 1
Future<T> submit (Runnable task, 
                T result)

提交可执行的任务并返回表示该任务的Future。 未来的get方法将在成功完成后返回给定的结果。

Parameters
task Runnable: the task to submit
result T: the result to return
Returns
Future<T> a Future representing pending completion of the task
Throws
RejectedExecutionException
NullPointerException

Protected methods

decorateTask

Added in API level 9
RunnableScheduledFuture<V> decorateTask (Runnable runnable, 
                RunnableScheduledFuture<V> task)

修改或替换用于执行可运行的任务。 此方法可用于覆盖用于管理内部任务的具体类。 默认实现只是返回给定的任务。

Parameters
runnable Runnable: the submitted Runnable
task RunnableScheduledFuture: the task created to execute the runnable
Returns
RunnableScheduledFuture<V> a task that can execute the runnable

decorateTask

Added in API level 9
RunnableScheduledFuture<V> decorateTask (Callable<V> callable, 
                RunnableScheduledFuture<V> task)

修改或替换用于执行可调用任务的任务。 此方法可用于覆盖用于管理内部任务的具体类。 默认实现只是返回给定的任务。

Parameters
callable Callable: the submitted Callable
task RunnableScheduledFuture: the task created to execute the callable
Returns
RunnableScheduledFuture<V> a task that can execute the callable

Hooray!