首先我們看下FutureTask與其他接口的關(guān)系圖
image.png
可以看到FutureTask實(shí)現(xiàn)了RunnableFuture,RunnableFuture繼承了Runnable和Future接口。
在我們的demo例子中 FutureTask如何得知線程執(zhí)行完畢的楷扬。
//FutureTask類
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;
//當(dāng)我們new出來FutureTask時(shí)候随橘,這個(gè)state為0
public FutureTask(Runnable runnable, V result) {
//調(diào)用了Executors中的方法
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
// Executors類
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
//在重寫call方法中會(huì)調(diào)用task的run方法。
public T call() {
task.run();
return result;
}
}
我們執(zhí)行線程start之后,因?yàn)镕utureTask實(shí)現(xiàn)了RunnableFuture维贺,RunnableFuture繼承了Runnable和Future接口澈圈,所以我們會(huì)運(yùn)行到FutureTask的run方法彬檀。
// FutureTask類
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 {
/*call會(huì)調(diào)用call中Runnable的run方法,所以 call會(huì)調(diào)用我們demo中
重寫的run方法 */
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
//如果正確執(zhí)行完run的內(nèi)容,則去置state的狀態(tài)
if (ran)
set(result);
}
} finally {
runner = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//修改state裝填并且喚醒掛起的線程
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
finishCompletion();
}
}
//當(dāng)任務(wù)執(zhí)行完畢會(huì)喚醒所有掛起的線程瞬女,這里的waiters是一個(gè)鏈表窍帝,后面會(huì)有說明
private void finishCompletion() {
for (WaitNode q; (q = waiters) != null;) {
// CAS直接將掛起線程鏈表waiters指向?yàn)榭? 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;
q = next;
}
break;
}
}
done();
callable = null;
}
在demo中,當(dāng)我們執(zhí)行FutureTask類的get方法時(shí)
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
// 獲取state的狀態(tài)
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;
//如果處于已經(jīng)完成或者異常狀態(tài)拆魏,直接返回
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//如果處于COMPLETING盯桦,則讓線程再次參與競(jìng)爭(zhēng)cpu
else if (s == COMPLETING)
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
//形成一個(gè)后進(jìn)先出的鏈表
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);
}
}
在上面的源碼中慈俯,我們可以看出來,awaitDone方法中我們會(huì)對(duì)比當(dāng)前state拥峦,如果state==new贴膘,我們會(huì)將線程掛起,等待finishCompletion方法中喚醒掛起的線程略号。
private V report(int s) throws ExecutionException {
Object x = outcome;
//如果線程正確執(zhí)行完畢刑峡,則返回結(jié)果,否則拋出異常
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}