Callable接口類似于Runnable,從名字就可以看出來了,但是Runnable不會返回結果,并且無法拋出返回結果的異常,而Callable功能更強大一些,被線程執行后,可以返回值,這個返回值可以被Future拿到,也就是說,Future可以拿到異步執行任務的返回值,下面來看一個簡單的例子
package com.future.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class MyTest {
// 接收在run方法中捕獲的異常,然后自定義方法拋出異常
//private static Throwable exception;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String result = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {//使用Callable接口作為構造參數
public String call() {
//真正的任務在這里執行,這里的返回值類型為String,可以為任意類型
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//exception = e;
//e.printStackTrace();
}
return "11111";
}});
executor.execute(future);
//在這里可以做別的任何事情
try {
result = future.get(5000, TimeUnit.MILLISECONDS); //取得結果,同時設置超時執行時間為5秒。同樣可以用future.get(),不設置執行超時時間取得結果
} catch (InterruptedException e) {
//System.out.println("任務已經取消");
future.cancel(true);
} catch (ExecutionException e) {
future.cancel(true);
} catch (TimeoutException e) {
future.cancel(true);
} finally {
executor.shutdown();
}
System.out.println("result:"+result);
}
/* public void throwException() throws FileNotFoundException, IOException {
if (exception instanceof FileNotFoundException)
throw (FileNotFoundException) exception;
if (exception instanceof IOException)
throw (IOException) exception;
}*/
}