定义
DOC:
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.
Method submit extends base method 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.)
翻译:
- 首先他是一个执行器(Executor),增强版的执行器:可以管理执行器的关闭。可以将异步任务包装成Future任务(跟踪任务的状态)
- 一个ExecutorService 可以被关闭,这样新的任务来了将会拒绝新的任务。方法为:shutdown(新的任务不执行,老的任务将等待其执行完成),shutdownNow(新任务不执行,老任务尝试关闭)。
- 其中的 submit方法基于 execute方法。他将会生成一个Future任务(可以被cancel和等待执行完成)
官方例子
网络任务的多线程处理:
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
}
}}
如下是关闭 ExecutorService的两个步骤:
- 拒绝新来的任务,等待老的任务去执行完毕。
- 调用shutdownNow gg思密达
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();
}
}}
直接子类 AbstractExecutorService
提供newTaskFor()方法,将runable,callable包装成RunnableFuture
结构:
由上图知:AbstractExecutorService 是对 ExcutorService的默认实现。
官方例子
public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
// ThreadPoolExecutor 继承自 ExecutorService
static class CustomTask implements RunnableFuture {...
protected RunnableFuture newTaskFor(Callable c) {
return new CustomTask (c);
}
protected RunnableFuture newTaskFor(Runnable r, V v) {
return new CustomTask (r, v);
}
// ... add constructors, etc.
}}
代码实现:
将runnable和callable包装成RunnableFuture