ExecutorService

来源:互联网 发布:八皇后问题最简单算法 编辑:程序博客网 时间:2024/05/19 02:43

All Superinterfaces:
Executor
All Known Subinterfaces:
ScheduledExecutorService
All Known Implementing Classes:
AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor


public interface ExecutorService extends Executor

An Executor that provides methods to manage termination(终止) and methods that can produce(生成) a Future for tracking(跟踪) progress(进展,进度) of one or more asynchronous tasks(跟踪一个或多个异步任务的进度).
An ExecutorService can be shut down, which will cause(原因,导致) it to reject(拒绝) new tasks. Two different(不同) methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously(先前,预先,早先) submitted tasks to execute before terminating(终止), while the shutdownNow() method prevents(防止,预防,阻止) waiting tasks from starting and attempts(尝试) to stop currently(目前) executing tasks. Upon termination(终止后), an executor has no tasks actively(活跃地) executing, no tasks awaiting execution, and no new tasks can be submitted(一旦终止,执行者没有任务主动执行,没有任务正在等待执行,并且不能提交新的任务). An unused ExecutorService should be shut down to allow reclamation of its resources(应该关闭一个未使用的ExecutorService以允许其资源的回收).

Method submit extends base method Executor.execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion(完成). Methods invokeAny and invokeAll perform(履行) the most commonly(常用) useful forms(形式) of bulk(大批) execution, executing a collection(收集) of tasks and then waiting for at least(最小) one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch(草图) of a network service in which threads in a thread pool service incoming requests(传入请求). It uses the preconfigured(预配置) Executors.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();   } }

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task(在将Runnable或Callable任务提交给ExecutorService之前,线程中的操作发生在该任务执行的任何操作之前), which in turn happen-before the result is retrieved via Future.get()(在结果通过Future.get()检索之前,这反过来发生。).

Since:
1.5

Methods inherited from interface java.util.concurrent.Executor

execute

Method Detail

shutdown

void shutdown()

Initiates(发起) an orderly(有序) shutdown in which previously(预先) submitted tasks are executed, but no new tasks will be accepted(接收). Invocation(调用) has no additional effect if already shut down(调用如果已经关闭,则不起作用。).
This method does not wait for previously(预先) submitted tasks to complete(完成) execution. Use awaitTermination to do that.

Throws:
SecurityException - if a security manager exists and shutting down this ExecutorService may manipulate(操作) threads that the caller is not permitted(合法的)(允许) to modify(修改) because it does not hold RuntimePermission(“modifyThread”), or the security manager’s checkAccess method denies access.

shutdownNow

List<Runnable> shutdownNow()

Attempts(尝试) to stop all actively(活跃地) executing tasks, halts(停止) the processing(处理) of waiting tasks, and returns a list of the tasks that were awaiting execution.
This method does not wait for actively executing tasks to terminate(终止). Use awaitTermination to do that.

There are no guarantees(保证,) beyond(以外) best-effort(最大努力) attempts(尝试) to stop processing actively executing tasks. For example, typical(典型) implementations will cancel via(通过) Thread.interrupt(), so any task that fails to respond to interrupts(打断) may never terminate(满期)(除了努力尝试停止处理积极执行任务之外,没有任何保证。
例如,典型的实现将通过Thread.interrupt()取消,所以任何不能响应中断的任务可能永远不会终止).

Returns:
list of tasks that never commenced execution
Throws:
SecurityException - if a security manager exists and shutting down this ExecutorService may manipulate threads that the caller is not permitted to modify because it does not hold RuntimePermission(“modifyThread”), or the security manager’s checkAccess method denies access.

isShutdown

boolean isShutdown()

Returns true if this executor has been shut down.
Returns:
true if this executor has been shut down

isTerminated

boolean isTerminated()

Returns true if all tasks have completed following shut down. Note that isTerminated is never true unless(除非) either(二者之一) shutdown or shutdownNow was called first.
Returns:
true if all tasks have completed following shut down

awaitTermination

boolean awaitTermination(long timeout,                         TimeUnit unit)                  throws InterruptedException

Blocks(阻塞) until(直到) all tasks have completed execution after a shutdown request, or the timeout occurs(发生), or the current thread is interrupted, whichever(任何) happens first(以先到者为准。).
Parameters:
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
true if this executor terminated(终止) and false if the timeout elapsed(过去) before termination
Throws:
InterruptedException - if interrupted while waiting

submit

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

Submits a value-returning(返回值的) task for execution and returns a Future representing(代表) the pending(待处理) results of the task. The Future’s get method will return the task’s result upon successful completion.
If you would like to immediately(立即) block waiting for a task, you can use constructions(构造) of the form result = exec.submit(aCallable).get();

Note: The Executors class includes a set of methods that can convert some other common closure-like objects, for example, PrivilegedAction to Callable form so they can be submitted.

Type Parameters:
T - the type of the task’s result
Parameters:
task - the task to submit
Returns:
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

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

Submits a Runnable task for execution and returns a Future representing that task. The Future’s get method will return the given result upon successful completion.
Type Parameters:
T - the type of the result
Parameters:
task - the task to submit
result - the result to return
Returns:
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

Future<?> submit(Runnable task)

Submits a Runnable task for execution and returns a Future representing(代表) that task. The Future’s get method will return null upon successful completion.
Parameters:
task - the task to submit
Returns:
a Future representing pending completion of the task
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if the task is null

invokeAll

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

Executes the given tasks, returning a list of Futures holding their status and results when all complete(执行给定的任务,返回持有其状态和结果的期货列表,当所有的完成). Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated(终止) either(两者之间) normally or by throwing an exception(请注意,完成的任务可能会正常终止或抛出异常). The results of this method are undefined if the given collection is modified while this operation is in progress(如果在此操作正在进行中修改给定集合,则此方法的结果是未定义的。).
Type Parameters:
T - the type of the values returned from the tasks
Parameters:
tasks - the collection of tasks
Returns:
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

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

Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires(执行给定的任务,当所有完成或超时到期时,返回持有其状态和结果的Futures列表), whichever happens first. Future.isDone() is true for each element of the returned list. Upon return, tasks that have not completed are cancelled(尚未完成的任务将被取消). Note that a completed task could have terminated either normally or by throwing an exception(请注意,完成的任务可能会正常终止或抛出异常). The results of this method are undefined if the given collection is modified while this operation is in progress.
Type Parameters:
T - the type of the values returned from the tasks
Parameters:
tasks - the collection of tasks
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
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

<T> T invokeAny(Collection<? extends Callable<T>> tasks)         throws InterruptedException,                ExecutionException

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do(执行给定的任务,返回一个已经成功完成的结果(即不抛出异常),如果有的话). Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.
Type Parameters:
T - the type of the values returned from the tasks
Parameters:
tasks - the collection of tasks
Returns:
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

<T> T invokeAny(Collection<? extends Callable<T>> tasks,                long timeout,                TimeUnit unit)         throws InterruptedException,                ExecutionException,                TimeoutException

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress.
Type Parameters:
T - the type of the values returned from the tasks
Parameters:
tasks - the collection of tasks
timeout - the maximum time to wait
unit - the time unit of the timeout argument
Returns:
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

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

原创粉丝点击