Callable與 Future 兩功能是Java 5版本中加入的,Callable是相似於Runnable的接口,實現Callable接口的類和實現Runnable的類。php
Callable的接口定義以下:java
public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
Callable和Runnable的區別以下:dom
Callable定義的方法是call,而Runnable定義的方法是run。異步
Callable的call方法能夠有返回值,而Runnable的run方法不能有返回值。spa
Callable的call方法可拋出異常,而Runnable的run方法不能拋出異常。code
Future定義orm
Future表示異步計算的結果,它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。Future的cancel方法能夠取消任務的執行,它有一布爾參數,參數爲 true 表示當即中斷任務的執行,參數爲 false 表示容許正在運行的任務運行完成。Future的 get 方法等待計算完成,獲取計算結果。接口
下面的示例中,咱們使用Callable來提交任務,使用Future來獲得執行的結果。get
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new Callable<String>() { public String call() throws Exception { Thread.sleep(2000); return "Hello"; }; }); System.out.println("Wait for result..."); try { System.out.println("Get the result:" + future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } threadPool.shutdown(); } }
運行結果:
Wait for result...
Get the result:Hello
it