java多線程前往值應用示例(callable與futuretask)。本站提示廣大學習愛好者:(java多線程前往值應用示例(callable與futuretask))文章只能為提供參考,不一定能成為您想要的結果。以下是java多線程前往值應用示例(callable與futuretask)正文
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;
}*/
}