常用线程池体系结构
- Executor:线程池顶级接口
- Executor Service:线程池次级接口,对Executor做了一些扩展,增加了一些功能
- Schedule Executor Service:对Executor Service做了一些扩展,增加了一些定时任务功能
- Abstract Executor Service:抽象类,运用模版方法设计模式实现了一部分方法;
- ThreadPool Executor:普通线程类,包含最基本的一些线程池操作相关的方法实现;
- Scheduled ThreadPool Executor:定时任务线程池类,用于实现定时任务相关功能;
- ForkJoinPool:新型线程池类,Java7中新增的线程池列,基于工作窃取理论实现,运用于大任务拆小任务,任务无限多的场景;
- Executors:线程池工具类,定义了一些快速实现线程池的方法;
Executor:
线程池顶级接口,定义了一个执行无返回值任务的方法,接口如下:
public interface Executor {
/**
* 执行无返回值任务
* 根据Executor的实现判断,可能是在新线程、线程池、线程调用中执行
*/
void execute(Runnable command);
}
Executor Service:
可以通过字面意思来理解,就是Executor + Service,在Executor的基础上扩展了一些线程池日常使用的一些状态或方法;
/**
* 关闭线程池,不再接受新任务,但已经提交的任务会执行完成
*/
void shutdown();
/**
* 立即关闭线程池,尝试停止正在运行的任务,未执行的任务将不再执行
* 被迫停止及未执行的任务将以列表的形式返回
*/
List<Runnable> shutdownNow();
/**
* 检查线程池是否已经关闭
*/
boolean isShutdown();
/**
* 检查线程池是否已经终止,只有在shutdown()或shutdownNow()之后调用才有可能为true
*/
boolean isTerminated();
/**
* 在指定时间内线程池达到终止状态了才会返回true
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 执行有返回值的任务,任务的返回值通过task.call()来查看
*/
<T>Future<T> submit(Runnable task);
/**
* 执行有返回值的任务,任务的返回值会存到传入的result中
* 只有当任务执行完成了调用get()时才会返回
*/
<T> Future<T> submit(Runnable task, T result);
/**
* 批量执行任务,只有当这些任务都完成了这个方法才会返回
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
/**
* 在指定时间内批量执行任务,未执行完成的任务将被取消
* timeout是所有任务的总时间,不是单个任务的时间
*/
<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;