国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java多線程返回值使用示例(callable與futuretask)

2019-11-26 15:33:33
字體:
來源:轉載
供稿:網友

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


}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曲水县| 攀枝花市| 阿鲁科尔沁旗| 涞源县| 宜黄县| 枣庄市| 台前县| 杭锦后旗| 资中县| 绥棱县| 沂南县| 玛纳斯县| 土默特右旗| 壤塘县| 阳城县| 梁平县| 思茅市| 普安县| 隆安县| 康定县| 宽城| 太保市| 平江县| 乌鲁木齐县| 云浮市| 景东| 富裕县| 南阳市| 洛隆县| 梁河县| 张家界市| 大姚县| 固原市| 奎屯市| 工布江达县| 鹿邑县| 定日县| 南充市| 中超| 高阳县| 大理市|