Java并發(fā)Futures和Callables類實例詳解
java.util.concurrent.Callable對象可以返回由線程完成的計算結(jié)果,而runnable接口只能運行線程。 Callable對象返回Future對象,該對象提供監(jiān)視線程執(zhí)行的任務(wù)進度的方法。 Future對象可用于檢查Callable的狀態(tài),然后線程完成后從Callable中檢索結(jié)果。 它還提供超時功能。
語法
//submit the callable using ThreadExecutor //and get the result as a Future object Future result10 = executor.submit(new FactorialService(10)); //get the result using get method of the Future object //get method waits till the thread execution and then return the result of the execution. Long factorial10 = result10.get();
實例
以下TestThread程序顯示了基于線程的環(huán)境中Futures和Callables的使用。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
System.out.println("Factorial Service called for 10!");
Future<Long> result10 = executor.submit(new FactorialService(10));
System.out.println("Factorial Service called for 20!");
Future<Long> result20 = executor.submit(new FactorialService(20));
Long factorial10 = result10.get();
System.out.println("10! = " + factorial10);
Long factorial20 = result20.get();
System.out.println("20! = " + factorial20);
executor.shutdown();
}
static class FactorialService implements Callable<Long>{
private int number;
public FactorialService(int number) {
this.number = number;
}
@Override
public Long call() throws Exception {
return factorial();
}
private Long factorial() throws InterruptedException{
long result = 1;
while (number != 0) {
result = number * result;
number--;
Thread.sleep(100);
}
return result;
}
}
}這將產(chǎn)生以下結(jié)果。
Factorial Service called for 10!
Factorial Service called for 20!
10! = 3628800
20! = 2432902008176640000
到此這篇關(guān)于Java并發(fā)Futures和Callables類的文章就介紹到這了,更多相關(guān)Java Futures和Callables類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMVC中的@ControllerAdvice使用場景詳解
這篇文章主要介紹了SpringMVC中的@ControllerAdvice使用場景詳解,在Spring?MVC進行調(diào)用的過程中,會有很多的特殊的需求,比如全局異常,分頁信息和分頁搜索條件,請求時帶來返回時還得回顯頁面,需要的朋友可以參考下2024-01-01
Spring Cloud Alibaba和Dubbo融合實現(xiàn)
這篇文章主要介紹了Spring Cloud Alibaba和Dubbo融合實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
java如何根據(jù)PostMan發(fā)送請求設(shè)置接口請求工具類
在Java中調(diào)用第三方接口可以通過不同的方式,如使用GET、POST等請求,關(guān)鍵點包括設(shè)置正確的請求方式、URL、參數(shù)(params)、頭信息(headers)和請求體(body),對于不同的數(shù)據(jù)格式,如XML和JSON,需在header中聲明內(nèi)容類型2024-09-09
Spring注解開發(fā)@Bean和@ComponentScan使用案例
這篇文章主要介紹了Spring注解開發(fā)@Bean和@ComponentScan使用案例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Java easyui樹形表格TreeGrid的實現(xiàn)代碼
這篇文章主要為大家詳細介紹了Java easyui樹形表格TreeGrid的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03

