1. Executor
整体架构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/229acc78d4a0bc01a2a41a06ecd33ecd.png)
接口/类 |
说明 |
Executor |
该接口只有一个execute 方法,目的是将任务提交和执行解耦 |
ExecutorService |
该接口对Executor 接口进行了拓展,定义了对线程池中线程的管理方法 |
AbstractExecutorService |
对ExecutorService接口中部分方法的实现 |
ThreadPoolExecutor |
线程池的最终实现,实现了线程池工作的完整机制,是整个框架的重点 |
ForkJoinPool |
实现了Fork/Join模式的线程池 |
ScheduleExecutorService |
对ExecutorService 进行了拓展,定义了延迟执行和周期执行任务的方法 |
ScheduleThreadExecutorService |
在继承ThreadPoolExecutorService 的基础上对ScheduleExecutorService 接口进行了实现 |
2. Executor
框架源码
2.1. Executor
接口
public interface Executor {
void execute(Runnable command);
}
2.2. ExecutorService
接口
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
<T> Future<T> submit(Runnable task, T result);
<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;
}
2.3. AbstractExecutorService
类
public abstract class AbstractExecutorService implements ExecutorService {
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
}
2.4. Executors
工具类
public class Executors {
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}