Execute框架是Java并发包里面的框架
简介
把任务的提交和执行解耦.
要执行任务的人只需把Task描述清楚,然后提交即可。这个Task是怎么被执行的,被谁执行的,什么时候执行的,提交的人就不用关心了。具体点讲,提交一个Callable对象给ExecutorService(如最常用的线程池ThreadPoolExecutor),将得到一个Future对象,调用Future对象的get方法等待执行结果就好了。
类结构
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}
按照层次结构看每个类的功能:
ExecutorService
定义了一个服务,定义了完整的线程池的行为,可以接受提交任务、执行任务、关闭服务
AbstractExecutorService
实现了ExecutorService接口,也实现了接口定义的默认行为。
ThreadPoolExecutor
实现了execute方法.
管理线程池.
请关注最重要的两个数据结构:
//任务队列
private final BlockingQueue<Runnable> workQueue;
//作业线程集合
private final HashSet<Worker> workers = new HashSet<Worker>();