java多線程傳回值使用樣本(callable與futuretask)_java

來源:互聯網
上載者:User

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;
     }*/


}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.