这篇文章将从以下几个方面讲述Excutor框架以及线程池:
。。。。
一、首先来看一下Executor框架的基本组成:
1. Executor是一个基础的接口,设计它的目的就是将任务的提交与任务的执行解耦,所以这个接口里就只定义了一个方法:excute(Runaable command);
源码:
1 public interface Executor { 2 //任务 3 /* @param command the runnable task 4 //几种饱和策略中,有一种饱和策略会抛出RejectedExecutionException 5 * @throws RejectedExecutionException if this task cannot be 6 * accepted for execution 7 //如果任务为null会抛出NullPointerException 8 * @throws NullPointerException if command is null 9 */ 10 void execute(Runnable command); 11 }
2.ExcutorService:不仅提供了列如shutdown的这种service的管理功能,也提供了能返回Future的的任务提交机制,而在其父接口Excutor中的提交方法不返回任何东西。
public interface ExecutorService extends Executor { //启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。 void shutdown(); boolean isTerminated(); //能返回Future而不是void的提交任务方法 <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task); ....... ....... ....... }
3.ThreadPolExecutor、ScheduledThreadPoolExecutor、ForkJoinPool则是Java标准类库为我们提供的几种基础实现。
4.Excutors则是从简化使用的角度,为我们提供了各种静态工厂方法方便我们直接调用;
以下的文章以ThreadPoolExecutor讲解:
二、线程池构造
我们首先看一下ThreadPoolExecutor的构造函数:
1 public ThreadPoolExecutor(int corePoolSize,//核心线程数量 2 int maximumPoolSize,//最大线程 3 long keepAliveTime, //存活时间 4 TimeUnit unit, //时间单位 5 BlockingQueue<Runnable> workQueue,//任务队列 6 ThreadFactory threadFactory//饱和策略(拒绝策略) 7 ) { 8 this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, 9 threadFactory, defaultHandler); 10 }
三、Excutors提供的几种线程池