在开启正文之前,我们先对线程池的继承体系有个大致的印象,究竟哪一个类代表线程池呢?
Executors只是一个帮助我们的工具类,它可以帮助我们定制化线程池(比如newFixedThreadPool(int nThreads)方法)。同时也在FutureTask中有所应用--统一 Callable 和 Runnable。
统一 Callable 和 Runnable
一种是有返回值的线程任务,一种是没有返回值的线程任务。
那么AbstractExecutorService是不是需要针对 Runnable 和 Callable 两种入参提供不同的实现思路呢?
不需要,因为Runnable 和 Callable无非就就两种差别:
1、Runnable没有返回值,Callable有返回值
2、Runnable的run()方法签名没有定义抛出异常,但是Callable的call()方法签名则定义了抛出异常。
面对这两种差别,我们使用适配器模式,适配器(RunnableAdapter)实现Callable接口。
Executors的内部静态类RunnableAdapter
static final class RunnableAdapter implements Callable {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
1、Runnable没有返回值,我们就自定义返回值result,虽然这并没有意义,但是能够启动统一输出线程结果操作。
2、Callable的call()方法签名定义了抛出异常,那我只要在(FutureTask)调用call()方法时,捕获异常。(注意这里RunnableAdapter虽然实现call方法时没有抛出异常,但是在调用时以接口的形式调用,所以还是要捕获异常的)
FutureTask类的方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
接下来我们聚焦到FutureTask。
FutureTask实现了Runnable, Future接口,组合了Callable。
1、实现了Runnable接口是能够让线程池调用其run()方法。
2、组合了Callable是能够让在调用run()方法中执行call()方法。
至于为什么实现Runnable接口,在run()方法中执行call()方法,主要是因为call()方法可能会抛出异常,而run方法不会。所以调用call()方法可能出现的情况必然是run()方法的父集。
FutureTask类
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result); //return new RunnableAdapter(task, result);
this.state = NEW; // ensure visibility of callable
}
AbstractExecutorService提供了入参为Runnable和Callable的方法,但是它通过FutureTask公用了一套实现逻辑。
AbstractExecutorService类
public Future> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
public Future submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
protected RunnableFuture newTaskFor(Runnable runnable, T value) {
return new FutureTask(runnable, value);
}
public Future submit(Callable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
protected RunnableFuture newTaskFor(Callable callable) {
return new FutureTask(callable);
}