Most visited

Recently visited

Added in API level 1

ExecutorService

public interface ExecutorService
implements Executor

java.util.concurrent.ExecutorService
Known Indirect Subclasses


一个 Executor ,提供了管理终止的方法和可以产生跟踪一个或多个异步任务进度的 Future方法。

一个ExecutorService可以关闭,这将导致它拒绝新的任务。 提供了两种不同的方法来关闭ExecutorService shutdown()方法将允许之前提交的任务在终止之前执行,而shutdownNow()方法阻止等待任务启动并尝试停止当前正在执行的任务。 终止时,执行者没有主动执行的任务,没有任务等待执行,也不能提交新的任务。 应关闭一个未使用的ExecutorService以便回收其资源。

方法submit延伸的基方法execute(Runnable)通过创建并返回一个Future可用于取消执行和/或等待完成。 方法invokeAnyinvokeAll执行最常用的批量执行形式,执行任务集合,然后等待至少一个或全部完成。 ExecutorCompletionService类可用于编写这些方法的定制变体。)

Executors类为此包中提供的执行程序服务提供工厂方法。

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured newFixedThreadPool(int) factory method:
 class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }

 class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

内存一致性效果:操作在提交之前的螺纹 RunnableCallable任务到 ExecutorService happen-before由任务采取的任何行动,这反过来又 发生-之前结果通过检索 Future.get()

Summary

Public methods

abstract boolean awaitTermination(long timeout, TimeUnit unit)

阻塞,直到所有任务在关闭请求之后所有任务都已完成执行,或发生超时,或当前线程中断,以先发生者为准。

abstract <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)

执行给定的任务,返回一份持有其状态和结果的期货清单,当全部完成时。

abstract <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)

执行给定的任务,当所有完成或超时到期时返回一份持有其状态和结果的期货清单,以先发生者为准。

abstract <T> T invokeAny(Collection<? extends Callable<T>> tasks)

执行给定的任务,返回已成功完成的任务(即,没有抛出异常)的结果,如果有的话。

abstract <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)

执行给定的任务,返回已成功完成的任务(即,没有抛出异常)的结果,如果在给定超时过去之前执行了任务。

abstract boolean isShutdown()

如果此执行者已被关闭,则返回 true

abstract boolean isTerminated()

如果所有任务在关闭后完成,则返回 true

abstract void shutdown()

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

abstract List<Runnable> shutdownNow()

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

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

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

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

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

abstract Future<?> submit(Runnable task)

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

Inherited methods

From interface java.util.concurrent.Executor

Public methods

awaitTermination

Added in API level 1
boolean awaitTermination (long timeout, 
                TimeUnit unit)

阻塞,直到所有任务在关闭请求之后所有任务都已完成执行,或发生超时,或当前线程中断,以先发生者为准。

Parameters
timeout long: the maximum time to wait
unit TimeUnit: the time unit of the timeout argument
Returns
boolean true if this executor terminated and false if the timeout elapsed before termination
Throws
InterruptedException if interrupted while waiting

invokeAll

Added in API level 9
List<Future<T>> invokeAll (Collection<? extends Callable<T>> tasks)

执行给定的任务,返回一份持有其状态和结果的期货清单,当全部完成时。 对于返回列表的每个元素, isDone()true 请注意, 完成的任务可能正常结束或通过抛出异常终止。 如果在进行此操作时修改了给定集合,则此方法的结果未定义。

Parameters
tasks Collection: the collection of tasks
Returns
List<Future<T>> a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed
Throws
InterruptedException if interrupted while waiting, in which case unfinished tasks are cancelled
NullPointerException if tasks or any of its elements are null
RejectedExecutionException if any task cannot be scheduled for execution

invokeAll

Added in API level 9
List<Future<T>> invokeAll (Collection<? extends Callable<T>> tasks, 
                long timeout, 
                TimeUnit unit)

执行给定的任务,当所有完成或超时到期时返回一份持有其状态和结果的期货清单,以先发生者为准。 isDone()对于返回列表的每个元素都是true 返回后,尚未完成的任务将被取消。 请注意, 完成的任务可能正常结束或通过抛出异常终止。 如果在进行此操作时修改了给定集合,则此方法的结果未定义。

Parameters
tasks Collection: the collection of tasks
timeout long: the maximum time to wait
unit TimeUnit: the time unit of the timeout argument
Returns
List<Future<T>> a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed.
Throws
InterruptedException if interrupted while waiting, in which case unfinished tasks are cancelled
NullPointerException if tasks, any of its elements, or unit are null
RejectedExecutionException if any task cannot be scheduled for execution

invokeAny

Added in API level 9
T invokeAny (Collection<? extends Callable<T>> tasks)

执行给定的任务,返回已成功完成的任务(即,没有抛出异常)的结果,如果有的话。 在正常或异常返回时,尚未完成的任务将被取消。 如果在进行此操作时修改了给定集合,则此方法的结果未定义。

Parameters
tasks Collection: the collection of tasks
Returns
T the result returned by one of the tasks
Throws
InterruptedException if interrupted while waiting
NullPointerException if tasks or any element task subject to execution is null
IllegalArgumentException if tasks is empty
ExecutionException if no task successfully completes
RejectedExecutionException if tasks cannot be scheduled for execution

invokeAny

Added in API level 9
T invokeAny (Collection<? extends Callable<T>> tasks, 
                long timeout, 
                TimeUnit unit)

执行给定的任务,返回已成功完成的任务(即,没有抛出异常)的结果,如果在给定超时过去之前执行了任务。 在正常或异常返回时,尚未完成的任务将被取消。 如果在进行此操作时修改了给定集合,则此方法的结果未定义。

Parameters
tasks Collection: the collection of tasks
timeout long: the maximum time to wait
unit TimeUnit: the time unit of the timeout argument
Returns
T the result returned by one of the tasks
Throws
InterruptedException if interrupted while waiting
NullPointerException if tasks, or unit, or any element task subject to execution is null
TimeoutException if the given timeout elapses before any task successfully completes
ExecutionException if no task successfully completes
RejectedExecutionException if tasks cannot be scheduled for execution

isShutdown

Added in API level 1
boolean isShutdown ()

如果此执行者已被关闭,则返回 true

Returns
boolean true if this executor has been shut down

isTerminated

Added in API level 1
boolean isTerminated ()

如果所有任务都在关闭后完成,则返回true 请注意, isTerminated永远不会是true除非首先调用shutdownshutdownNow

Returns
boolean true if all tasks have completed following shut down

shutdown

Added in API level 1
void shutdown ()

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

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

shutdownNow

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

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

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

除了竭尽全力尝试停止处理主动执行的任务之外,没有任何保证。 例如,典型的实现将通过interrupt()取消,所以任何不能响应中断的任务都不会终止。

Returns
List<Runnable> list of tasks that never commenced execution

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 if the task cannot be scheduled for execution
NullPointerException if the task is null

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 if the task cannot be scheduled for execution
NullPointerException if the task is null

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 if the task cannot be scheduled for execution
NullPointerException if the task is null

Hooray!