概述
FutureTask 是一个可取消的、异步执行任务的类,它实现了 RunnableFuture 接口,而该接口又继承了 Runnable 接口和 Future 接口,因此 FutureTask 也具有这两个接口所定义的特征。
RunnableFuture 接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
Future 接口
/*
* 尝试取消执行任务。若任务已完成、已取消,或者由于其他某些原因无法取消,则尝试失败。
* 若成功,且调用该方法时任务未启动,则此任务不会再运行;
* 若任务已启动,则根据参数 mayInterruptIfRunning 决定是否中断该任务。
*/
boolean cancel(boolean mayInterruptIfRunning);
// 若该任务正常结束之前被取消,则返回 true
boolean isCancelled();
/*
* 若该任务已完成,则返回 true
* 这里的“完成”,可能是由于正常终止、异常,或者取消,这些情况都返回 true
*/
boolean isDone();
// 等待计算完成(如果需要),然后获取结果
V get() throws InterruptedException, ExecutionException;
// 如果需要,最多等待计算完成的给定时间,然后检索其结果(如果可用)
// PS: 该方法与前者的区别在于加了超时等待
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
源码分析
构造方法
// 创建一个 FutureTask 对象,在运行时将执行给定的 Callable
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
// 创建一个 FutureTask,在运行时执行给定的 Runnable,
// 并安排 get 将在成功完成时返回给定的结果
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
这两个构造器分别传入 Callable 对象和 Runnable 对象(适配为 Callable 对象),然后将其状态初始化为 NEW。
成员变量
//与任务相关变量
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
//其他变量
/** The underlying callable; nulled out after running */
// 提交的任务
private Callable<V> callable;
/** The result to return or exception to throw from get() */
// get() 方法返回的结果(或者异常)
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
// 执行任务的线程
private volatile Thread runner;
/** Treiber stack of waiting threads */
// 等待线程的 Treiber 栈
private volatile WaitNode waiters;
其中 state 表示任务的状态,总共有 7 种,它们之间的状态转换可能有以下 4 种情况:
任务执行正常:NEW -> COMPLETING -> NORMAL
任务执行异常:NEW -> COMPLETING -> EXCEPTIONAL
任务取消:NEW -> CANCELLED
任务中断:NEW -> INTERRUPTING -> INTERRUPTED
内部类
对 Thread 的封装
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
常用方法
1.任务执行 run()方法
public void run() {
// 使用 CAS 进行并发控制,防止任务被执行多次
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// 调用 Callable 的 call 方法执行任务
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);
}
}
2.获取执行结果get()方法
// 获取执行结果(阻塞式)
public V get() throws InterruptedException, ExecutionException {
int s = state;
// 若任务未执行完,则等待它执行完成
if (s <= COMPLETING)
// 任务未完成
s = awaitDone(false, 0L);
// 封装返回结果
return report(s);
}
// 获取执行结果(有超时等待)
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
这两个方法都是获取任务执行的结果,原理也基本一样,区别在于后者有超时等待(超时会抛出 TimeoutException 异常)。
其他方法后续学习补充~