在 多線程實現(xiàn)方式 文中講述了幾種開啟多線程的方式温兼,每種方式都有其特定的使用場景,本文將剖析帶有返回值的線程實現(xiàn)方式赊抖。FutureTask類關(guān)系如下:
首先看FutureTask的兩個構(gòu)造方法:
//構(gòu)造方法一
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
//構(gòu)造方法二
public FutureTask(Runnable runnable, V result) {
//將runnable包裝成callable
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
第一個構(gòu)造方法我們比較熟悉,第二個構(gòu)造方法可以用 Runnable 構(gòu)造 FutureTask不跟,將 Runnable 使用適配器模式 構(gòu)造成 FutureTask 柒巫,使其具有 FutureTask 的特性励堡,如可在主線程捕獲Runnable的子線程異常。
構(gòu)造完FutureTask堡掏,就可以用FutureTask構(gòu)造Thread应结,并啟動線程。啟動線程會調(diào)用FutureTask的run()方法泉唁,run()方法是FutureTask的實現(xiàn)關(guān)鍵:
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的異常處理關(guān)鍵
setException(ex);
}
if (ran)
//3亭畜、設(shè)置返回值
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;
//設(shè)置為異常狀態(tài)
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL);
finishCompletion();
}
}
//設(shè)置正常返回值
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
//設(shè)置為正常結(jié)束狀態(tài)
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
在run()方法中扮休,會調(diào)用callable對象的call()方法,并獲取方法返回值拴鸵,同時對call()方法中的異常進行了處理玷坠。異常時會將outcome設(shè)置為拋出的異常,正常時會將outcome設(shè)置為正常返回值劲藐,并將state設(shè)置成相應(yīng)狀態(tài)八堡。
run()分析完,下一步就要分析future.get()獲取線程返回結(jié)果時如何工作聘芜。
public V get() throws InterruptedException, ExecutionException {
int s = state;
//未完成兄渺,則進入阻塞狀態(tài),等待完成
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s); //判斷處理返回值
}
private V report(int s) throws ExecutionException {
Object x = outcome;
//根據(jù)state判斷線程處理狀態(tài)汰现,并對outcome返回結(jié)果進行強轉(zhuǎn)挂谍。
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x); //在主線程中拋出異常
}
分析完run()方法和get()方法,其實對于FutureTask的返回值獲取原理有了基本了解瞎饲。下面繼續(xù)分析其他要點:
1口叙、線程狀態(tài)
//FutureTask定義的7種線程狀態(tài)
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1; //設(shè)置返回值的過程,這個狀態(tài)很短企软,可以劃分為已完成狀態(tài)庐扫。參考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;
}
線程的狀態(tài)在執(zhí)行過程不同階段不斷變化仗哨,這是FutureTask的狀態(tài)控制關(guān)鍵。注意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;
} //正在處理返回值,這里時間很短旨椒,所以調(diào)用Thread.yield()方法晓褪,短時間的線程讓步。
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null) //創(chuàng)建等待節(jié)點
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的流程涣仿,暗含很多優(yōu)化邏輯,值得思考示惊。
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()會在一下三處被調(diào)用:
在任務(wù)被取消、正常完成或執(zhí)行異常時會調(diào)用finishCompletion()方法米罚,從而喚醒等待隊列中的線程钧汹。
多線程系列目錄(不斷更新中):
線程啟動原理
線程中斷機制
多線程實現(xiàn)方式
FutureTask實現(xiàn)原理
線程池之ThreadPoolExecutor概述
線程池之ThreadPoolExecutor使用
線程池之ThreadPoolExecutor狀態(tài)控制
線程池之ThreadPoolExecutor執(zhí)行原理
線程池之ScheduledThreadPoolExecutor概述
線程池之ScheduledThreadPoolExecutor調(diào)度原理
線程池的優(yōu)雅關(guān)閉實踐