標籤:catch [] system print pre ice exe and 4.0
啟動一個線程不論使用Thread或者Runnable的時候。都是沒有返回結果的。
也就是說Thread和Runnable的run()方法必須沒有傳回值。
public void run(){}
解決方式:
Callable和Future,一個產生結果,一個拿到結果。
簡單的來一個執行個體demo協助我們理解:
public class CallableAndFuture {/** * @param args */public static void main(String[] args) {//單一線程的線程池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("等待結果");try {System.out.println("拿到結果" + future.get());} catch (InterruptedException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}
運行結果:
等待結果
拿到結果hello
使用情境:
如果有一個非常耗時的傳回值須要計算。而且這個傳回值不是立馬須要的話,那麼就能夠使用以上這樣的方式,用還有一個線程去計算傳回值,而當前線程在使用這個傳回值之前能夠做其他的操作,等到須要這個傳回值時,再通過Future得到!
說明:
Future取得的結果類型和Callable返回的結果類型必須一致,這是通過泛型來實現的
Callable要採用ExecutorService的submit方法提交,返回為future對象
CompletionService用於提交一組Callable任務,其take方法返回已完畢的一個Callable任務相應的Future對象
好比我同一時候種了幾塊地的麥子,然後就等待收割。收割時,哪塊先成熟,則先收割哪塊
以下我們來針對CompletionService看一個小demo
public class CallableAndFuture {/** * @param args */public static void main(String[] args) {ExecutorService threadPool2 = Executors.newFixedThreadPool(10);CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);for(int i=1;i<=10;i++){final int seq = i;completionService.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {Thread.sleep(new Random().nextInt(5000));return seq;}});}for(int i=0;i<10;i++){try {System.out.println(completionService.take().get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}}}
運行結果:
8
6
5
7
2
1
3
10
9
4
總結:
對於多線程運行返回結果這樣的需求在實際應用中還是非常少見的,此文僅僅是作為瞭解學習。
JAVA 並發編程-返回運行結果(Callable和Future)(九)