FutureTask原始碼分析

2022-03-22 01:03:10 字數 3817 閱讀 9658

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;

//run正常執行:new -> completing -> normal

//run異常執行:new -> completing -> exceptional

//cancel(false):new -> cancelled

//cancel(true):new -> interrupting -> interrupted

private callablecallable; //

任務private object outcome; //

執行結果

private

volatile thread runner; //

任務執行執行緒(在run方法中置為當前執行緒)

private

volatile waitnode waiters; //

任務等待鍊錶(頭節點)

public futuretask(callablecallable) 

public

futuretask(runnable runnable, v result)

static

final

class

waitnode

}

public

booleancancel(boolean

mayinterruptifrunning) finally}}

finally

return

true;}

private

void

finishcompletion()

waitnode next = q.next;

if (next == null

)

break

; q.next = null

; q =next;

}break

; }

}done();

//noop

callable = null;

}protected

void done()

public

booleaniscancelled()

public

booleanisdone()

public vget() 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)

else

if (s == completing) //

任務執行中thread.yield();

else

if (q == null) //

任務尚未執行(s == new),則建立任務等待節點qq = new waitnode();else

if (!queued) //

q尚未排隊,則cas設定q為頭節點queued = unsafe.compareandswapobject(this, waitersoffset, q.next = waiters, q);else

if (timed)locksupport.parknanos(this, nanos); //

在naos時間內等待}

elselocksupport.park(

this); //

永久等待}

}private

void

removewaiter(waitnode node)

// q已被喚醒 && q前不存在未被喚醒節點,則cas設定頭節點為q.nextelse

if (!unsafe.compareandswapobject(this, waitersoffset, q, s))continue

retry;

}break

; }

}}

public

void

run() catch(throwable ex)

if(ran)set(result);//

設定正常的執行結果}

} finally

}protected

void

set(v v)

}protected

void

setexception(throwable t)

}private

void handlepossiblecancellationinterrupt(int

s)

private

static

final

sun.misc.unsafe unsafe;

private

static

final

long

stateoffset;

private

static

final

long

runneroffset;

private

static

final

long

waitersoffset;

static

catch

(exception e)

}

FutureTask原始碼分析

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

FutureTask原始碼分析筆記

futuretask實際上執行還是乙個runnable,它對callable做了乙個封裝,讓開發人員可以從其中獲取返回值 futruetask是有狀態的 共7種狀態,四種狀態變換的可能 new completing exceptional new cancelled new completing n...

FutureTask 原始碼閱讀

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