### FutureTask
用Runnable提交异步任务是没有返回值的,如果需要返回值的异步任务,使用Callable接口。
例子:
public static class CallAbleTask implements Callable<String> {
@Override
public String call() throws Exception {
String ret = "this is callable task test";
return ret;
}
}
上面有返回值的实现原理是什么?
答案是使用FutureTask。
FutureTask的构造函数:将Callable实现类封装为FutureTask,它实现了Runnable接口,之后调用
execute(futureTask)即可执行,下面分析futureTask源码。
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
任务有成员变量state记录状态:
- 任务的初始状态都是
NEW
, 这一点是构造函数保证的,我们后面分析构造函数的时候再讲; - 任务的终止状态有4种:
NORMAL
:任务正常执行完毕EXCEPTIONAL
:任务执行过程中发生异常CANCELLED
:任务被取消INTERRUPTED
:任务被中断
- 任务的中间状态有2种:
-
COMPLETING
正在设置任务结果 -
INTERRUPTING
正在中断运行任务的线程
-
FutureTaskd的run代码,用来运行callable实现类的call。该方法将cal的返回结果设置到对象变量result里,当运行结束后将task的状态设置为NORMAL(final state),唤醒因提早获取结果而阻塞的线程。
public void run() {
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 {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
//调完call方法,开始把结果放入
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);
}
}
调完call方法,开始把得到的result存入对象变量里
protected void set(V v) {
//更新对象的任务状态
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//结果放入outcome
outcome = v;
//更新对象的任务状态
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//遍历整个等待队列链表,唤醒线程,gc掉这些等待线程node
finishCompletion();
}
}
遍历整个等待队列链表,唤醒线程,gc掉这些等待线程node
private void finishCompletion() {
// assert state > COMPLETING;
//遍历等待队列
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
//子类可以覆盖此函数,callable任务执行完就会执行done();
done();
callable = null; // to reduce footprint
}
获取结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//s<=completing即任务还没运行完,调用awaitDone,挂起线程
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) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
//s == COMPLETING即任务刚刚运行完,让出cpu等一会
//“运行状态”进入到“就绪状态”。然后再在for循环内
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
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);
}
}