package java.util.concurrent; public interface Future<V> { //試圖取消對此任務的執行 boolean cancel(boolean mayInterruptIfRunning); //若是在任務正常完成前將其取消,則返回 true boolean isCancelled(); //若是任務已完成,則返回 true boolean isDone(); //若有必要,等待計算完成,而後獲取其結果 V get() throws InterruptedException, ExecutionException; //若有必要,最多等待爲使計算完成所給定的時間以後,獲取其結果(若是結果可用) V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
類型參數:html
V
- 此 Future 的 get 方法所返回的結果類型java
全部已知子接口:api
Response<T>, RunnableFuture<V>, RunnableScheduledFuture<V>, ScheduledFuture<V>異步
全部已知實現類:spa
FutureTask, SwingWorker.net
Future 表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並獲取計算的結果。線程
計算完成後只能使用 get 方法來獲取結果,若有必要,計算完成前能夠阻塞此方法。取消則由 cancel 方法來執行。還提供了其餘方法,以肯定任務是正常完成仍是被取消了。code
一旦計算完成,就不能再取消計算。若是爲了可取消性而使用 Future 但又不提供可用的結果,則能夠聲明 Future<?> 形式類型、並返回 null 做爲底層任務的結果。xml
用法示例(注意,下列各種都是構造好的。)htm
interface ArchiveSearcher {
String search(String target);
}
class App {
ExecutorService executor = ...
ArchiveSearcher searcher = ...
void showSearch(final String target) throws InterruptedException {
Future<String> future = executor.submit(new Callable<String>() {
public String call() {
return searcher.search(target);
}
});
displayOtherThings(); // do other things while searching
try {
displayText(future.get()); // use future
} catch (ExecutionException ex) { cleanup(); return; }
}
}
FutureTask
類是 Future 的一個實現, Future 可實現 Runnable,因此可經過 Executor 來執行。例如,可用下列內容替換上面帶有 submit 的構造:
FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
public String call() {
return searcher.search(target);
}
});
executor.execute(future);
boolean cancel(boolean mayInterruptIfRunning)
試圖取消對此任務的執行。若是任務已完成、或已取消,或者因爲某些其餘緣由而沒法取消,則此嘗試將失敗。當調用 cancel 時,若是調用成功,而此任務還沒有啓動,則此任務將永不運行。若是任務已經啓動,則 mayInterruptIfRunning 參數肯定是否應該以試圖中止任務的方式來中斷執行此任務的線程。
此方法返回後,對 isDone()
的後續調用將始終返回 true。若是此方法返回 true,則對 isCancelled()
的後續調用將始終返回 true。
參數:
mayInterruptIfRunning
- 若是應該中斷執行此任務的線程,則爲 true;不然容許正在運行的任務運行完成
返回:
若是沒法取消任務,則返回 false,這一般是因爲它已經正常完成;不然返回 true
boolean isCancelled()
若是在任務正常完成前將其取消,則返回 true。
返回:
若是任務完成前將其取消,則返回 true
boolean isDone()
若是任務已完成,則返回 true。 可能因爲正常終止、異常或取消而完成,在全部這些狀況中,此方法都將返回 true。
返回:
若是任務已完成,則返回 true
V get() throws InterruptedException, ExecutionException
若有必要,等待計算完成,而後獲取其結果。
返回:
計算的結果
拋出:
CancellationException
- 若是計算被取消
ExecutionException
- 若是計算拋出異常
InterruptedException
- 若是當前的線程在等待時被中斷
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
若有必要,最多等待爲使計算完成所給定的時間以後,獲取其結果(若是結果可用)。
參數:
timeout
- 等待的最大時間
unit
- timeout 參數的時間單位
返回:
計算的結果
拋出:
CancellationException
- 若是計算被取消
ExecutionException
- 若是計算拋出異常
InterruptedException
- 若是當前的線程在等待時被中斷
TimeoutException
- 若是等待超時