本篇說明的是callable和future,它倆很有意思的,乙個產生結果,乙個拿到結果。
callable介面類似於runnable,從名字就可以看出來了,但是runnable不會返回結果,並且無法丟擲返回結果的異常,而callable功能更強大一些,被執行緒執行後,可以返回值,這個返回值可以被future拿到,也就是說,future可以拿到非同步執行任務的返回值,
public class taskwithcallable implements callable
@override
public string call() throws exception
public static void main(string args) catch (interruptedexception e) catch (executionexception e) finally}}
}result of taskwithcallable0
result of taskwithcallable1
result of taskwithcallable2
result of taskwithcallable3
result of taskwithcallable4
result of taskwithcallable5
callable介面:
public inte***ce callable
runnable介面:
public inte***ce runnable
相同點:
兩者都是介面;(廢話)
兩者都可用來編寫多執行緒程式;
兩者都需要呼叫thread.start()啟動執行緒;
不同點:
兩者最大的不同點是:實現callable介面的任務執行緒能返回執行結果;而實現runnable介面的任務執行緒不能返回結果;
callable介面的call()方法允許丟擲異常;而runnable介面的run()方法的異常只能在內部消化,不能繼續上拋;
專案例子:
1:定義多執行緒類:實現callable介面;
重寫call方法:call方法的返回值是circdodetaildataorgresult ,然後circdodetaildataorgresult 的實現類中有retcode,errbuf兩個屬性,分別是作為執行多執行緒的call方法的返回結果和返回值!
public class circcreatexmlcallable implements callable
@override
public circdodetaildataorgresult call() catch (exception e)
return result;
}2:呼叫執行緒類,執行執行緒方法;
①首先使用threadpoolexecutor executor = (threadpoolexecutor) executors.newfixedthreadpool(threadcount);建立執行緒池;
②接下來listcallables = new arraylist(); list中的circcreatexmlcallable就是步驟1中定義的執行緒類,這個list用來裝執行緒類;
:然後生成執行緒類的例項mycallable ;將mycallable加入到list中去,callables.add(mycallable);
:list> futurelist = executor.invokeall(callables);執行緒池executor啟動,執行
執行緒中的call方法,然後用future介面將執行緒執行返回的結果接收到,future.get()得到結果!
例子2:
list>> result接收返回的結果,結果為map型別的map集合;
返回結果:
Runnable與Callable的比較
public inte ce callable public inte ce runnable 相同點 兩者都是介面 兩者都可用來編寫多執行緒程式 兩者都需要呼叫thread.start 啟動執行緒 不同點 兩者最大的不同點是 實現callable介面的任務執行緒能返回執行結果 而實現runnabl...
多執行緒 Callable與Future模式
future常用方法 v get 獲取非同步執行的結果,如果沒有結果可用,此方法會阻塞直到非同步計算完成。v get long timeout timeunit unit 獲取非同步執行結果,如果沒有結果可用,此方法會阻塞,但是會有時間限制,如果阻塞時間超過設定的timeout時間,該方法將丟擲異常...
多執行緒中Future與Callable理解及使用
對於實現runnable介面的執行緒,執行過程中無法得到物件的返回值,callbale介面就可以做到獲取執行緒執行的結果.每乙個任務都是乙個執行緒,利用executeorservice.submit來提交,然後返回future物件,這個物件有任務的生命週期,提供了相應的方法來判斷是否已經完成或者取消...