定義
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.)
翻譯:
- 首先他是一個執(zhí)行器(Executor)匾七,增強(qiáng)版的執(zhí)行器:可以管理執(zhí)行器的關(guān)閉〗ぃ可以將異步任務(wù)包裝成Future任務(wù)(跟蹤任務(wù)的狀態(tài))
- 一個ExecutorService 可以被關(guān)閉昨忆,這樣新的任務(wù)來了將會拒絕新的任務(wù)。方法為:shutdown(新的任務(wù)不執(zhí)行杉允,老的任務(wù)將等待其執(zhí)行完成)邑贴,shutdownNow(新任務(wù)不執(zhí)行,老任務(wù)嘗試關(guān)閉)叔磷。
- 其中的 submit方法基于 execute方法拢驾。他將會生成一個Future任務(wù)(可以被cancel和等待執(zhí)行完成)
官方例子
網(wǎng)絡(luò)任務(wù)的多線程處理:
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
}
}}
如下是關(guān)閉 ExecutorService的兩個步驟:
- 拒絕新來的任務(wù),等待老的任務(wù)去執(zhí)行完畢改基。
- 調(diào)用shutdownNow gg思密達(dá)
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
結(jié)構(gòu):
由上圖知:AbstractExecutorService 是對 ExcutorService的默認(rèn)實現(xiàn)。
官方例子
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.
}}
代碼實現(xiàn):
將runnable和callable包裝成RunnableFuture