Executor(二):Future jdk1.8


如果使用異步計算就離不開Future,Future提供了一些方法方便對異步任務進行處理。

 JDK對Future的描述

Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. 


 一個Future代表一個異步計算的結果。提供了檢測計算是否完成等待計算完成取回計算的結果。結果只能通過get方法獲取當計算完成,阻塞如果必須直到它準備好。通過cancel方法去取消執行。其他的方法被提供去判斷任務正常完成或已經被取消。 一旦一個計算完成,這個計算不能被取消。

 

Future是一個接口,你可以實現這個接口根據自己的業務擴展出自己的自定義的Future,但是一般都會使用JDK自帶的一些Furure。

Future提供的主要方法

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

After this method returns, subsequent calls to isDone() will always return true. Subsequent calls to isCancelled() will always return true if this method returned true.

嘗試去取消這個任務的執行。這個嘗試將會失敗如果任務已經完成,已經取消,或 因爲一些其他原因不能被取消。如果成功並且這個任務沒有開始當調用cancel方法時 這個任務將會永不執行。如果這個任務已經開始執行,然後mayInterruptIfRunning參數 決定是否線程執行這個任務應不應該被中斷去停止這個任務。

之後會調用isDone和isCancelled方法。

 

boolean isCancelled()

Returns true if this task was cancelled before it completed normally.

返回true如果任務已經在正常執行完成前取消。

boolean isDone()

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

如果任務完成將會返回true.可能是因爲正常終止,一個異常或取消這些所有情況都將會返回true。

V get() 和V get(long timeout,TimeUnit unit)

Waits if necessary for the computation to complete, and then retrieves its result.

等待計算完成,然後獲取到結果。 

 

參考資料:

jdk1.8源碼 

發佈了33 篇原創文章 · 獲贊 0 · 訪問量 6181
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章