Contents

先看看Executor中的各个类和接口关系图,如下

Executor框架类图

从上图可知,ExecutorService继承于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.
Executor提供管结束异步任务的方法,同时提供一个方法生成Future对象,此对象用来追踪一个或者多个异步任务的运行状况。
An ExecutorService can be shut down, which will cause it to reject new
tasks.
通过关闭ExecutorService,可以拒绝接受新的任务。
Two different methods are provided for shutting down an
ExecutorService.
其中提供了2个不同的方法来关闭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.
shutdown方法允许在ExecutorService关闭之前完成已提交的任务,然而shutdownNow方法阻止正在等待的任务,并且尝试着停止正在运行的任务
Upon termination, an executor has no tasks actively
executing, no tasks awaiting execution, and no new tasks can be
submitted.
一旦终止了服务,将没有任务在executor中执行,没有任务等待executor的执行,也没有任务提交。
An unused ExecutorService should be shut down to allow
reclamation of its resources.
不在使用的executorService对象将被关闭同时java虚拟机将回收其资源。

Method submit extends base method Executor.execute(java.lang.Runnable)
by creating and returning a Future that can be used to cancel execution
and/or wait for completion.
submit方法继承于Executor.execute方法,其通过创建和返回一个Future的实现对象来管理任务的执行,例如取消任务的执行和等待任务的完成。
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.
方法invokeAny和invokeAll用来执行一个多个任务,invokeAny方法的调用将会阻塞当前线程,直至执行的线程里面有一个线程执行完则返回。
而invokeAll方法则阻塞等待所有任务执行完。
(Class ExecutorCompletionService can be used to write customized variants of
these methods.)
(ExecutorCompletionService是用来实现用户自定义以上方法的基本类。)

The Executors class provides factory methods for the executor services
provided in this package.
Executors提供创建接口ExecutorService不同实现的工厂方法。

i下面是ExecutorService中定义的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public interface ExecutorService extends Executor{
void shutdown();
List<Runnable> shutdown();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException,
ExecutionException, TimeoutException;
}

下一篇将学习ExecutorService的具体实现和每个方法的具体应用。

Contents