Java5之前,線程是沒有返回值的。Java5之后,可以寫有返回值的任務了。
有返回值的任務必須實現Callable接口,沒有返回值的任務實現Runnable接口。
執行Callable接口后,可以獲得一個Future的一個對象,通過Feture的get方法就能獲得返回的Object數據了。
代碼如下:
public class ThreadExtend_Pool_Return_Value {
public static void main(String args[]) throws ExecutionException, InterruptedException {
//創建一個線程池
ExecutorService executorService= Executors.newFixedThreadPool(2);
//創建有兩個返回值的線程
Callable callable1=new CallableImpl("callable1");
Callable callable2=new CallableImpl("callable2");
//執行任務並獲取future對象
Future future1=executorService.submit(callable1);
Future future2=executorService.submit(callable2);
//從future獲取返回值,並輸出到控制台
System.out.println(">>>>"+future1.get().toString());
System.out.println(">>>>"+future2.get().toString());
//關閉線程池
executorService.shutdown();
}
}
/**
* 有返回值的線程需要實現Callable接口
*/
class CallableImpl implements Callable{
private String oid;
CallableImpl(String oid){
this.oid=oid;
}
@Override
public Object call(){
return this.oid+"任務返回的內容";
}
}
運行后,結果如下:
>>>>callable1任務返回的內容
>>>>callable2任務返回的內容