1. 程式人生 > >Future, FutureTask的作用和差異

Future, FutureTask的作用和差異

Future是一個介面,表示一個任務的週期,並提供了相應的方法來判斷是否已經完成或者取消任務,以及獲取任務的結果和取消任務。

下面根據Future的定義介紹一下相關的介面


1. boolean cancel(boolean mayInterruptIfRunning);

取消任務.
fail的情況:任務已經完成,已經被取消過了,無法取消。
success的情況:任務還沒有開始執行,其他由引數mayInterruptIfRunning決定。
若mayInterruptIfRunning為true,任務不可以被打斷。
否則就可以允許完成。

當該方法被執行過之後,isDone()的結果輸出一直為true.
如果該方法return true,isCancelled的結果輸出一直為true.

return:false,如果任務不能被取消一般是因為已經被正常執行。

2.  boolean isCancelled();

檢測在任務正常執行之前是否被取消。
3.   boolean isDone();

Return true is this task completed.
任務的完成包括正常的結束,exception,和取消。

4. V get() throws InterruptedException, ExecutionException;

阻塞等待任務完成,並獲取計算結果。

@throws CancellationException if the computation was cancelled
@throws ExecutionException if the computation threw an exception
@throws InterruptedException if the current thread was interrupted  while waiting


5. V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

阻塞等待任務完成或者timeout的時間到了,然後獲取計算結果。

@param timeout the maximum time to wait
@param unit the time unit of the timeout argument
@return the computed result
@throws CancellationException if the computation was cancelled
@throws ExecutionException if the computation threw an exception
@throws InterruptedException if the current thread was interrupted while waiting
@throws TimeoutException if the wait timed out


Future是一個介面,FutureTask是Future的一個實現類,並實現了Runnable,因此FutureTask可以傳遞到執行緒物件Thread中新建一個執行緒執行。所以可以通過Excutor(執行緒池)來執行,也可傳遞給Thread物件執行。

如果在主執行緒中需要執行比較耗時的操作,但又不想阻塞主執行緒時,可以把這些作業交給Future物件在後臺完成,當主執行緒將來需要時,就可以通過Future物件獲得後臺作業的計算結果或者執行狀態。 

FutureTask是為了彌補Thread的不足而設計的,它可以讓程式設計師準確地知道執行緒什麼時候執行完成並獲得到執行緒執行完成後返回的結果(如果有需要)。
FutureTask是一種可以取消的非同步的計算任務。它的計算是通過Callable實現的,它等價於可以攜帶結果的Runnable,並且有三個狀態:等待、執行和完成。完成包括所有計算以任意的方式結束,包括正常結束、取消和異常。
Executor框架利用FutureTask來完成非同步任務,並可以用來進行任何潛在的耗時的計算。一般FutureTask多用於耗時的計算,主執行緒可以在完成自己的任務後,再去獲取結果。

JDK:

此類提供了對 Future 的基本實現。僅在計算完成時才能檢索結果;如果計算尚未完成,則阻塞 get 方法。一旦計算完成,就不能再重新開始或取消計算。


可使用 FutureTask 包裝 Callable 或 Runnable 物件。因為 FutureTask 實現了 Runnable,所以可將 FutureTask 提交給 Executor 執行。