针对各种池子,比如
首先看看UML图:
可以看到最顶层的接口是Executor,就是线程池的顶层接口,线程池的作用就是执行方法,而Executor方法里面就一个方法:
void execute(Runnable command);
这个方法就是线程池最主要的方法,执行runnable任务,然后ExecutorService又对线程池的功能进行了加强,比如可以进行管理线程池,且提供了执行任务的能力,比如执行异步返回Future结果的方法,执行多个任务的方法;
最主要的构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
这些方法基本都是创建ThreadPoolExecutor,或者继承ThreadPoolExecutor,对其进行增强.
默认的拒绝策略是AbortPolicy,直接抛出异常
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}