JAVA 並發編程-返回運行結果(Callable和Future)(九)

來源:互聯網
上載者:User

標籤: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)(九)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.