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)文章
分布式開發(fā)醫(yī)療掛號系統(tǒng)數(shù)據(jù)字典模塊前后端實現(xiàn)
這篇文章主要為大家介紹了分布式開發(fā)醫(yī)療掛號系統(tǒng)數(shù)據(jù)字典模塊前后端實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04Spring Boot集成Seata實現(xiàn)基于AT模式的分布式事務(wù)的解決方案
Seata 是一款開源的分布式事務(wù)解決方案,致力于提供高性能和簡單易用的分布式事務(wù)服務(wù),這篇文章主要介紹了Spring Boot集成Seata實現(xiàn)基于AT模式的分布式事務(wù),需要的朋友可以參考下2024-08-08Java Swing中的JButton、JComboBox、JList和JColorChooser組件使用案例
這篇文章主要介紹了Java Swing中的按鈕(JButton)、組合框(JComboBox)、下拉列表(JList)和顏色選擇器(JColorChooser)組件使用案例,需要的朋友可以參考下2014-10-10