在 多線程實現方式 文中講述了幾種開啟多線程的方式,每種方式都有其特定的使用場景,本文將剖析帶有返回值的線程實現方式。FutureTask類關系如下:
首先看FutureTask的兩個構造方法:
//構造方法一
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
//構造方法二
public FutureTask(Runnable runnable, V result) {
//將runnable包裝成callable
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
第一個構造方法我們比較熟悉,第二個構造方法可以用 Runnable 構造 FutureTask,將 Runnable 使用適配器模式 構造成 FutureTask ,使其具有 FutureTask 的特性,如可在主線程捕獲Runnable的子線程異常。
構造完FutureTask,就可以用FutureTask構造Thread,并啟動線程。啟動線程會調用FutureTask的run()方法,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 {
//1、獲取返回值
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//2、FutureTask的異常處理關鍵
setException(ex);
}
if (ran)
//3、設置返回值
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);
finishCompletion();
}
}
//設置正常返回值
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
//設置為正常結束狀態
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
在run()方法中,會調用callable對象的call()方法,并獲取方法返回值,同時對call()方法中的異常進行了處理。異常時會將outcome設置為拋出的異常,正常時會將outcome設置為正常返回值,并將state設置成相應狀態。
run()分析完,下一步就要分析future.get()獲取線程返回結果時如何工作。
public V get() throws InterruptedException, ExecutionException {
int s = state;
//未完成,則進入阻塞狀態,等待完成
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s); //判斷處理返回值
}
private V report(int s) throws ExecutionException {
Object x = outcome;
//根據state判斷線程處理狀態,并對outcome返回結果進行強轉。
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x); //在主線程中拋出異常
}
分析完run()方法和get()方法,其實對于FutureTask的返回值獲取原理有了基本了解。下面繼續分析其他要點:
1、線程狀態
//FutureTask定義的7種線程狀態
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1; //設置返回值的過程,這個狀態很短,可以劃分為已完成狀態。參考isDone()方法;
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;
//是否已取消
public boolean isCancelled() {
return state >= CANCELLED;
}
//是否已完成
public boolean isDone() {
return state != NEW;
}
線程的狀態在執行過程不同階段不斷變化,這是FutureTask的狀態控制關鍵。注意state是volatile修飾,保障了多線程間的可見性。
2、阻塞等待
線程status為NEW和COMPLETING的時候,會進入awaitDone方法,表示要等待完成。awaitDone方法如下:
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;
} //正在處理返回值,這里時間很短,所以調用Thread.yield()方法,短時間的線程讓步。
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null) //創建等待節點
q = new WaitNode();
else if (!queued) //CAS把該線程加入等待隊列
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的流程,暗含很多優化邏輯,值得思考。
3、喚醒
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;
}
}
done();
callable = null; // to reduce footprint
}
finishCompletion()會在一下三處被調用:
在任務被取消、正常完成或執行異常時會調用finishCompletion()方法,從而喚醒等待隊列中的線程。
多線程系列目錄(不斷更新中):
線程啟動原理
線程中斷機制
多線程實現方式
FutureTask實現原理
線程池之ThreadPoolExecutor概述
線程池之ThreadPoolExecutor使用
線程池之ThreadPoolExecutor狀態控制
線程池之ThreadPoolExecutor執行原理
線程池之ScheduledThreadPoolExecutor概述
線程池之ScheduledThreadPoolExecutor調度原理
線程池的優雅關閉實踐