FutureTask原始碼閱讀與理解

2021-08-14 18:55:09 字數 2407 閱讀 9733

futuretask原始碼閱讀與理解

簡述:futuretask實現了runnable和future介面,代表此類可以被執行緒池排程和非同步執行任務。

幾個變數:

//以下是state的幾種狀態

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;

//具體任務

private callablecallable;

//任務執行完畢結果存放屬性

private object outcome;

//記錄執行任務的執行緒

private

volatile thread runner;

//鍊錶結構,表示等待結果的執行緒

private

volatile waitnode waiters;

幾個方法:

//run方法就是執行任務的方法

public

void

run() catch (throwable ex)

//如果執行成功則執行set方法

if (ran)

set(result);

}} finally

}protected

void

set(v v)

}private

void

finishcompletion()

waitnode next = q.next;

if (next == null)

break;

q.next = null; // unlink to help gc

q = next;

}break;}}

//完成任務並喚醒所有等待結果執行緒再執行done方法

done();

callable = null; // to reduce footprint

}//獲取資料的方法,可限時:

public v get() throws interruptedexception, executionexception

public v get(long timeout, timeunit unit)

throws interruptedexception, executionexception, timeoutexception

//具體的取值-等待方法

private

intawaitdone(boolean timed, long nanos)

throws interruptedexception

//如果大於已完成則返回

int s = state;

if (s > completing)

//說明執行任務的執行緒正在給outcome賦值,讓掉cpu

else

if (s == completing) // cannot time out yet

thread.yield();

//如果q==null那就建立乙個等待節點

else

if (q == null)

q = new waitnode();

//試著加入佇列

else

if (!queued)

queued = unsafe.compareandswapobject(this, waitersoffset,q.next = waiters, q);

//是否有設定超時時間

else

if (timed)

locksupport.parknanos(this, nanos);

}//掛起執行緒

else

locksupport.park(this);

}}

FutureTask 原始碼閱讀

public void run catch throwable ex if ran set result finally get操作的核心方法 private intawaitdone boolean timed,long nanos throws interruptedexception int ...

FutureTask原始碼分析

futuretask實現了runnablefuture,runnablefuture繼承了runnable和future介面。future介面和實現future介面的futuretask類,代表非同步計算的結果。所以futuretask既能當做乙個runnable直接被thread執行,也能作為fu...

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 ...