Java非同步Future詳解

2021-08-15 09:42:18 字數 2559 閱讀 9551

future主要用於有返回值的非同步任務。最核心的類是futuretask,它是future介面唯一的實現類。

可以看出futuretask類實現了runnable和future介面。

內部屬性有

private

volatile

int state;

private callablecallable;

/** the result to return or exception to throw from get() */

private object outcome; // non-volatile, protected by state reads/writes

/** the thread running the callable; cased during run() */

private

volatile thread runner;

/** treiber stack of waiting threads */

private

volatile waitnode waiters;

其中

有兩周建構函式,分別傳入runnable物件和callable物件

public

futuretask(callablecallable)

public

futuretask(runnable runnable, v result)

當傳入建構函式的物件是runnable時,呼叫executors.callable(runnable,result)方法返回乙個callable的介面卡,這個介面卡的call方法會呼叫runnable的run方法,並固定返回傳入的result物件。

在run方法呼叫callable的call方法,並把返回結果賦值給outcome屬性。

public

void

run() catch (throwable ex)

if (ran)

set(result);

}} finally

}

用於獲取執行的結果,如果沒有執行完則阻塞等待,可以設定超時時間。

public v get() throws interruptedexception, executionexception
在get方法中呼叫awaitdone方法阻塞等待。awaitdone方法會把當前呼叫get的執行緒yield掛起並放在乙個鍊錶中,執行完成之後會一一喚醒

private

intawaitdone(boolean timed, long nanos)

throws interruptedexception

int s = state;

if (s > completing)

else

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

thread.yield();

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);}}

private

void

finishcompletion()

waitnode next = q.next;

if (next == null)

break;

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

q = next;

}break;}}

done();

callable = null; // to reduce footprint

}

可以直接使用callable或者包裝成futuretask

public

static

void

main(string args) throws executionexception, interruptedexception

}class mytask implements callable catch (interruptedexception e)

return

"hello from mytask!";

}

016 非同步處理 Future

用於在單獨的執行緒中執行程序,cpu空閒時。future注釋來標識非同步執行的方法。當使用同步處理時,所有方法呼叫都從執行apex 的同一執行緒進行,並且在該過程完成之前不會發生額外的處理。你可以使用 future的方法來執行任何你希望在自己的執行緒中非同步執行的操作。這提供了不阻止使用者執行其他操...

訪問非同步操作結果 future

一 std future 通常乙個非同步操作我們是不能馬上就獲取操作結果的,只能在未來某個時候獲取。我們可以以同步等待的方式來獲取結果,可以通過查詢future的狀態 future status 來獲取非同步操作的結果。future status有三種狀態 1.deferred 非同步操作還沒開始 ...

flutter中的非同步機制Future

dart是乙個單執行緒語言,可以理解成物理線路中的串聯,當其遇到有延遲的運算 比如io操作 延時執行 時,執行緒中按順序執行的運算就會阻塞,使用者就會感覺到卡頓,於是通常用非同步處理來解決這個問題。dart非同步程式設計有兩種方式 future和stream future相當於40公尺大砍刀,str...