Thread pool series:
- [JUC source code] thread pool: ThreadPoolExecutor (1) inheritance relationship analysis
- [JUC source code] Thread pool: ThreadPoolExecutor (two) underlying structure analysis
- [JUC source code] Thread pool: ThreadPoolExecutor (3) Worker design ideas and source code analysis
- [JUC source code] Thread pool: ThreadPoolExecutor (four) source code analysis of task execution process
- [JUC source code] thread pool: ThreadPoolExecutor (5) summary
- [JUC source code] Thread pool: Parameter setting ideas for creating thread pool &Excutors
- [JUC source code] Thread Pool: Several questions about ThreadPool
Before looking at the source code of ThreadPoolExecutor, let's take a look at the inheritance relationship of ThreadPoolExecutor
1.Executor
Define the execute method to execute the task, the input parameter is Runnable, no output parameter
public interface Executor {
void execute(Runnable command);
}
2.ExecutorService
The function of Executor is too weak. ExecutorService enriches the functions of task execution and management. The main code is as follows:
public interface ExecutorService extends Executor {
// 提交有返回值的任务,使用 get 方法可以阻塞等待任务的执行结果返回
<T> Future<T> submit(Callable<T> task);
// 提交没有返回值的任务,如果使用 get 方法的话,任务执行完之后得到的是 null 值
Future<?> submit(Runnable task);
// 给定任务集合,返回已经执行完成的 Future 集合,每个返回的 Future 都是 isDone = true 的状态
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
// 给定任务中有一个执行成功就返回,如果抛异常,其余未完成的任务将被取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
// 关闭,不会接受新的任务,也不会等待未完成的任务
// 如果需要等待未完成的任务,可以使用 awaitTermination 方法
void shutdown();
// 在超时时间内,等待剩余的任务终止
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
// executor 是否已经关闭了,返回值 true 表示已关闭
boolean isShutdown();
// 所有的任务是否都已经终止,是的话,返回 true
boolean isTerminated();
}
3.AbstractExecutorService
- Abstract class, which encapsulates many general functions of Executor
- Implemented some ExecutorService methods
public abstract class AbstractExecutorService implements ExecutorService {
// 将Callabbe,想要返回值的Runnable转化成Callable
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
// FutureTask(Runnable,T) -> RunnableFuture -> Runnable
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
// submit调用的还是execute
// 只不过将Callable,要返回值的Runnable提前转化成了RunnableFuture
// 提交无返回值的任务
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
// ftask 其实是 FutureTask
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
// 提交有返回值的任务
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
// ftask 其实是 FutureTask
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
}