### 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);
}
}