Interface Future Java Doc全解

本文翻譯自Java Docbash

正文

相關接口

Type Parameters:
V - 表明這個接口提供的get方法的返回值類型app

全部的子接口:異步

  • Response
  • RunnableFuture
  • RunnableScheduledFuture
  • ScheduledFuture

全部的實現類:async

  • CompletableFuture
  • CountedCompleter
  • ForkJoinTask
  • FutureTask
  • RecursiveAction
  • RecursiveTask
  • SwingWorker

概述

Future表明一個異步的計算結果。它提供了一些方法來檢查Future的計算是否完畢,你能夠等待計算完畢直到你獲得計算結果。當Future的計算結束時,你能夠經過get()方法來獲取計算結果。其餘的方法能夠去判斷計算是否完成,或者是否已被取消。若是一個計算已經完成,那麼這個計算就沒法取消了。必要時,實現類能夠將get方法設計成阻塞的,只有計算成功纔會返回結果。調用cancel方法能夠取消計算。若是計算還沒有完成,你也能夠將get方法的返回值設置爲null。ui

一個簡單的用例:spa

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和Runnable接口,因此能夠作爲Executor.execute方法的參數。線程

因此上面的樣例代碼能夠簡化爲以下代碼:翻譯

FutureTask<String> future =
   new FutureTask<String>(new Callable<String>() {
     public String call() {
       return searcher.search(target);
   }});
executor.execute(future);
複製代碼

下面內存一致性影響這個不太理解,有大神看到能夠幫忙翻譯一下設計

Memory consistency effects: Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.code

方法

boolean cancel(boolean mayInterruptIfRunning)

嘗試取消任務。若是這個任務已經結束或者已經被取消,那麼此方法會調用失敗,固然了,也可能由於一些其餘緣由致使取消失敗。若是取消成功,並且這個任務還未開始執行以前就調用了cancel方法,那麼這麼任務應該不再會執行。若是這個任務已經開始執行了,那麼是否應該中斷線程來取消任務的執行,是由mayInterruptIfRunning這個參數決定執行的。只要這個方法被執行過一次,後續全部對isDone()方法的調用永遠都返回true。後續全部對isCancelled() 方法的調用永遠也都返回true。

Parameters:
mayInterruptIfRunning - 若是執行任務的線程應該被終止,那麼就傳true ; 不然在進行中的任務會容許其繼續執行

Returns:
若是任務沒法被取消就會返回false,這種狀況通常都是由於任務已經執行完畢了。其餘狀況會返回true。

boolean isCancelled()

若是任務正常執行以前被取消,那麼返回true.

Returns:
任務執行前取消成功會返回true

boolean isDone()

若是任務已經完成,那麼返回true。可是任務已完成有不少種因素,例如正常終止,任務失敗並拋出異常,或者被取消,這些狀況下該方法都會返回true。

Returns:
任務已完成時會返回true

V get() throws InterruptedException,ExecutionException

若是有必要的話,在計算完畢以前此方法會一直阻塞,計算完畢後會返回結果。

Returns:
返回計算結果

Throws:
CancellationException - 若是任務已經被取消
ExecutionException - 若是計算過程當中拋出了異常
InterruptedException - 若是等待的線程被中斷

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

若是必要的話,在計算完畢以前此方法會阻塞一段時間,直到阻塞時間大於參數指定時間,若是一切正常會返回結果

Parameters:
timeout - 最大的等待時間
unit - 時間單位

Returns:
計算結果

Throws: CancellationException - 若是任務已經被取消 ExecutionException - 若是計算過程當中拋出了異常 InterruptedException - 若是等待的線程被中斷 TimeoutException - 若是等待時間超時

相關文章
相關標籤/搜索