简介
FutureTask实现了RunnableFuture,RunnableFuture继承了Runnable和Future接口。Future接口和实现Future接口的FutureTask类,代表异步计算的结果。所以FutureTask既能当做一个Runnable直接被Thread执行,也能作为Future用来得到异步计算的结果。
用法
public static class MyFutureTask implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("MyFutureTask start......");
Thread.sleep(2000);
System.out.println("MyFutureTask end......");
return "Hello World";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new MyFutureTask());
// 启动线程
// FutureTask实现了RunnableFuture,RunnableFuture继承了Runnable
// 所以FutureTask既能当做一个Runnable直接被Thread执行
new Thread(futureTask).start();
// 获取执行结果
String result = futureTask.get();
System.out.println("MyFutureTask result : " + result);
System.out.println("Main end");
}
主要属性
/**
* 对象的状态
* NEW -> COMPLETING -> NORMAL 任务正常执行并返回
* NEW -> COMPLETING -> EXCEPTIONAL 执行中出现异常
* NEW -> CANCELLED 任务执行过程中被取消,并且不响应中断
* NEW -> INTERRUPTING -> INTERRUPTED 任务执行过程中被取消,并且响应中断
*/
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; // 任务线程已中断
// 用户提交的任务
private Callable<V> callable;
// 任务的执行结果
private Object outcome; // non-volatile, protected by state reads/writes
// 执行任务的线程
private volatile Thread runner;
// 等待节点,存储的是调用get()而被阻塞的线程
private volatile WaitNode waiters;
// 内部类
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
// 构造函数
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // 设置对象状态
}
public FutureTask(Runnable runnable, V result) {
// 这里的result为返回结果
this.callable = Executors.callable(runnable, result); // 将Runnable转换为Callable
this.state = NEW; // ensure visibility of callable
}
主要方法
// 线程启动之后,最后会调用FutureTask的run方法
public void run() {
// 如果state不为NEW,或者设置runner为当前运行的线程失败则直接返回
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
// callable为用户提交的任务
// 这里开始提交任务
Callable<V> c = callable;
// 用户不能提交一个空任务并且state必须为NEW时才能执行任务
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);
}
}
// 设置异常信息
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
// 设置返回结果
protected void set(V v) {
// 将state从NEW状态更改为COMPLETING状态
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v; // 设置任务的返回结果
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // 最后将任务状态设置为NORMAL
finishCompletion(); // 最后调用完成方法
}
}
private void finishCompletion() {
// waiters存储的的是调用get()方法而被阻塞的线程
for (WaitNode q; (q = waiters) != null;) {
// 如果waiters不为空
// 则将waiters设置为null
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread; // 获取调用get()方法的线程
if (t != null) {
q.thread = null;
LockSupport.unpark(t); // 唤醒调用get()方法的线程
}
WaitNode next = q.next; // 获取下一个调用get()方法的线程
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
// 钩子方法,由子类重写的,在FutureTask里面什么也没做
done();
// 任务置空
callable = null; // to reduce footprint
}
// 用户获取任务返回结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
// 如果state小于等于COMPLETING,则进入队列等待
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s); // 返回结果
}
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
// 如果当前线程已经被中断了,则将当前线程从等待队列中删除
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
// state 大于 COMPLETING直接返回
if (q != null)
q.thread = null;
return s;
}
// 如果状态等于COMPLETING,说明任务快完成了,就差设置状态到NORMAL或EXCEPTIONAL和设置结果了
// 这时候就让出CPU,优先完成任务
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode(); // 如果q为null,说明当前线程第一次进入for循环
else if (!queued) // 如果当前线程没有进入waiters队列,则尝试入队
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) { // 这里判断是否超时
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
// 如果已经超时,则删除对应节点并返回对应的状态
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this); // 阻塞当前线程,等待被唤醒
}
}
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x; // 任务正常结束
if (s >= CANCELLED)
throw new CancellationException(); // 任务被取消
throw new ExecutionException((Throwable)x);
}
总结
- 实现Callable接口并构造一个FutureTask对象。
- 线程启动之后会调用FutureTask的run方法,run方法会执行我们实现的call方法,任务执行完成后将会设置任务的返回结果,并唤醒waiters队列里面的线程。
- 用户调用FutureTask的get()方法获取任务的执行结果,若任务还没有执行完成,则将当前线程放到等待队列waiters并阻塞当前线程。任务执行完毕后,waiters里面的线程将会被唤醒。