java中Future使用方法舉例詳細(xì)介紹
一、什么是Future?
在并發(fā)編程中,可以通過Future對(duì)象來異步獲取結(jié)果。
使用Thread或runnable接口都不能獲取異步的執(zhí)行結(jié)果,因?yàn)樗麄儧]有返回值。而通過實(shí)現(xiàn)Callable接口和Future就可以獲取異步執(zhí)行的結(jié)果,當(dāng)異步執(zhí)行結(jié)束后,返回結(jié)果將保存在Future中。使用Future就可以讓我們暫時(shí)去處理其他的任務(wù)而無需一直等待結(jié)果,等異步任務(wù)執(zhí)行完畢再返回其結(jié)果。
二、Future中的get方法
1、get方法
獲取任務(wù)結(jié)束后返回的結(jié)果,如果調(diào)用時(shí),任務(wù)還沒有結(jié)束,則會(huì)進(jìn)行阻塞線程,直到任務(wù)完成。該阻塞是可以被打斷的,打斷的線程是調(diào)用get方法的線程,被打斷后原任務(wù)會(huì)依舊繼續(xù)執(zhí)行。
V get() throws InterruptedException, ExecutionException;
2、指定時(shí)間的get方法
獲取任務(wù)結(jié)束后返回的結(jié)果,如果調(diào)用時(shí),任務(wù)還沒有結(jié)束,則會(huì)進(jìn)行阻塞線程,等待一定時(shí)間,如果在規(guī)定時(shí)間內(nèi)任務(wù)結(jié)束則返回結(jié)果,否則拋出TimeoutException,超時(shí)后任務(wù)依舊會(huì)繼續(xù)執(zhí)行。該阻塞是可以被打斷的,打斷的線程是調(diào)用get方法的線程,被打斷后原任務(wù)會(huì)依舊繼續(xù)執(zhí)行。
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
三、Future代碼示例
步驟1:創(chuàng)建一個(gè)線程池
public class AsyncTaskExecutor { /** * 核心線程數(shù) */ private static final int corePoolSize = 10; /** * 最大線程數(shù) */ private static final int maxPoolSize = 30; /** * 空閑線程回收時(shí)間 * 空閑線程是指:當(dāng)前線程池中超過了核心線程數(shù)之后,多余的空閑線程的數(shù)量 */ private static final int keepAliveTime = 100; /** * 任務(wù)隊(duì)列/阻塞隊(duì)列 */ private static final int blockingQueueSize = 99999; private static final ThreadPoolExecutor executorPool = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(blockingQueueSize), new ThreadFactoryBuilder().setNameFormat("AsyncTaskThread" + "-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy() ); /** * 異步任務(wù)執(zhí)行 * * @param task */ public static void execute(Runnable task) { executorPool.execute(task); } /** * 異步執(zhí)行任務(wù)Callable, 通過Future獲取結(jié)果 * * @param task * @param <T> * @return */ public static <T> Future<T> submit(Callable<T> task) { return executorPool.submit(task); } /** * 異步執(zhí)行任務(wù)Runnable,通過Future獲取結(jié)果 * * @param task * @return */ public static Future<?> submit(Runnable task) { return executorPool.submit(task); } }
步驟2:編寫測(cè)試類
@Test public void test2() { try { Future<String> future = AsyncTaskExecutor.submit(() -> { log.info("[Future Task] future task start..."); try { //模擬任務(wù)執(zhí)行 Thread.sleep(5000); } catch (InterruptedException e) { log.info(e.getMessage()); } log.info("[Future Task] future task end..."); return "Task completed..."; }); //執(zhí)行其他任務(wù) log.info("[Main Thread] main thread is running..."); //使用future阻塞等待任務(wù)完成,并獲取結(jié)果 String futureResult = future.get(); log.info("[Main Thread] {}", futureResult); }catch (Exception e) { e.printStackTrace(); } }
步驟3:查看結(jié)果
2024-05-28 10:58:23.633 INFO 1184 --- [ main] com.example.demo.dao.UserDaoTest : [Main Thread] main thread is running... 2024-05-28 10:58:23.633 INFO 1184 --- [yncTaskThread-0] com.example.demo.dao.UserDaoTest : [Future Task] future task start... 2024-05-28 10:58:28.633 INFO 1184 --- [yncTaskThread-0] com.example.demo.dao.UserDaoTest : [Future Task] future task end... 2024-05-28 10:58:28.634 INFO 1184 --- [ main] com.example.demo.dao.UserDaoTest : [Main Thread] Task completed...
四、ListenableFuture
public class AsyncTaskExecutor { /** * 核心線程數(shù) */ private static final int corePoolSize = 10; /** * 最大線程數(shù) */ private static final int maxPoolSize = 30; /** * 空閑線程回收時(shí)間 * 空閑線程是指:當(dāng)前線程池中超過了核心線程數(shù)之后,多余的空閑線程的數(shù)量 */ private static final int keepAliveTime = 100; /** * 任務(wù)隊(duì)列/阻塞隊(duì)列 */ private static final int blockingQueueSize = 99999; private static final ThreadPoolExecutor executorPool = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(blockingQueueSize), new ThreadFactoryBuilder().setNameFormat("AsyncTaskThread" + "-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy() ); /** * 創(chuàng)建一個(gè)ListeningExecutorService,用于執(zhí)行異步任務(wù) * (通過submit提交任務(wù),以ListenableFuture獲取結(jié)果) */ private static final ListeningExecutorService LISTENING_EXECUTOR = MoreExecutors.listeningDecorator(executorPool); /** * 異步任務(wù)執(zhí)行 * * @param task */ public static void execute(Runnable task) { executorPool.execute(task); } /** * 異步執(zhí)行任務(wù)Callable, 通過ListenableFuture獲取結(jié)果 * * @param task * @param <T> * @return */ public static <T> ListenableFuture<T> submit(Callable<T> task) { return LISTENING_EXECUTOR.submit(task); } /** * 異步執(zhí)行任務(wù)Runnable,通過Future獲取結(jié)果 * * @param task * @return */ public static ListenableFuture<?> submit(Runnable task) { return LISTENING_EXECUTOR.submit(task); } }
//示例1: @Test public void test2() { ListenableFuture<School> listenableFuture1 = AsyncTaskExecutor.submit(() -> { try { //模擬任務(wù)執(zhí)行 Thread.sleep(2000); } catch (InterruptedException e) { log.info(e.getMessage()); } return new School("DSchool"); }); ListenableFuture<School> listenableFuture2 = AsyncTaskExecutor.submit(() -> { try { //模擬任務(wù)執(zhí)行 Thread.sleep(3000); } catch (InterruptedException e) { log.info(e.getMessage()); } return new School("ESchool"); }); //阻塞等待,直到listenableFuture1 和 listenableFuture2都獲取到結(jié)果后或其中一個(gè)異常 Futures.successfulAsList(listenableFuture1, listenableFuture2).get(); School resSchool1 = listenableFuture1.get(); School resSchool2 = listenableFuture2.get(); log.info("[Main Thread] result1 is {}", JSON.toJSONString(resSchool1)); log.info("[Main Thread] result2 is {}", JSON.toJSONString(resSchool2)); //任意位置即時(shí)設(shè)定ListenableFuture的返回結(jié)果 ListenableFuture<School> listenableFuture3 = Futures.immediateFuture(new School("aaa")); ListenableFuture<School> listenableFuture4 = Futures.immediateFailedFuture(new Exception("eeee")); log.info("[Main Thread] listenableFuture3 is {}", listenableFuture3.get()); log.info("[Main Thread] listenableFuture4 is {}", listenableFuture4.get()); }catch (Exception e) { e.printStackTrace(); } } //示例2: public static void main(String[] args) { // 創(chuàng)建一個(gè)ListeningExecutorService,用于執(zhí)行異步任務(wù) ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); // 提交一個(gè)異步任務(wù),并得到ListenableFuture對(duì)象 ListenableFuture<String> listenableFuture = executor.submit(() -> { // 模擬耗時(shí)操作 Thread.sleep(2000); return "Result of the asynchronous computation"; }); // 注冊(cè)異步操作完成時(shí)的回調(diào)函數(shù) Futures.addCallback(listenableFuture, new FutureCallback<String>() { @Override public void onSuccess(String result) { System.out.println("Result: " + result); executor.shutdown(); // 關(guān)閉executor } @Override public void onFailure(Throwable t) { t.printStackTrace(); executor.shutdown(); // 關(guān)閉executor } }, executor); }
五、CompletableFuture
//示例1: public static void main(String[] args) { // 創(chuàng)建一個(gè)CompletableFuture對(duì)象 CompletableFuture<School> completableFuture = new CompletableFuture<>(); // 異步任務(wù):模擬一個(gè)耗時(shí)操作 new Thread(() -> { try { // 模擬耗時(shí)操作 Thread.sleep(2000); // 完成CompletableFuture并設(shè)置值 completableFuture.complete(new School("completableSchool")); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); // 在這里等待異步任務(wù)的結(jié)果并輸出 try { School result = completableFuture.get(); log.info("[CompletableFuture] result is {}" ,result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } //示例2: @Test public void test2() { try { //創(chuàng)建一個(gè)CompletableFuture對(duì)象 CompletableFuture<School> schoolFuture = new CompletableFuture<>(); //任意位置即時(shí)設(shè)定CompletableFuture的返回結(jié)果 schoolFuture.complete(new School("FSchool")); School school = schoolFuture.get(); log.info("[Main Thread] result is {}", JSON.toJSONString(school)); }catch (Exception e) { log.info(e.getMessage()); } }
六、SettableFuture
//示例1: public static void main(String[] args) { // 創(chuàng)建一個(gè)SettableFuture對(duì)象 SettableFuture<String> settableFuture = SettableFuture.create(); // 手動(dòng)設(shè)置異步操作的結(jié)果 settableFuture.set("Result of the asynchronous computation"); // 注冊(cè)異步操作完成時(shí)的回調(diào)函數(shù) settableFuture.addListener(() -> { try { String result = settableFuture.get(); // 獲取異步操作的結(jié)果 System.out.println("Result: " + result); } catch (Exception e) { e.printStackTrace(); } }, Runnable::run); } //示例2: @Test public void test2() { try { //創(chuàng)建一個(gè)SettableFuture對(duì)象 SettableFuture<School> settableFuture = SettableFuture.create(); //任意位置即時(shí)設(shè)定SettableFuture的返回結(jié)果 settableFuture.set(new School("GSchool")); School setSchool = settableFuture.get(); log.info("[Main Thread] setSchool is {}", JSON.toJSONString(setSchool)); }catch (Exception e) { log.info(e.getMessage()); } }
總結(jié)
到此這篇關(guān)于java中Future使用方法的文章就介紹到這了,更多相關(guān)java中Future使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Java事件監(jiān)聽編寫一個(gè)中秋猜燈謎小游戲
眾所周知,JavaSwing是Java中關(guān)于窗口開發(fā)的一個(gè)工具包,可以開發(fā)一些窗口程序,然后由于工具包的一些限制,導(dǎo)致Java在窗口開發(fā)商并沒有太多優(yōu)勢(shì),不過,在JavaSwing中關(guān)于事件的監(jiān)聽機(jī)制是我們需要重點(diǎn)掌握的內(nèi)容,本文將基于Java事件監(jiān)聽編寫一個(gè)中秋猜燈謎小游戲2023-09-09Springboot手動(dòng)連接庫(kù)并獲取指定表結(jié)構(gòu)的示例代碼
這篇文章主要介紹了Springboot手動(dòng)連接庫(kù)并獲取指定表結(jié)構(gòu)的示例代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(42)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07Java中system.exit(0) 和 system.exit(1)區(qū)別
本文主要介紹了Java中system.exit(0) 和 system.exit(1)區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05SpringBoot中@ConfigurationProperties注解實(shí)現(xiàn)配置綁定的三種方法
這篇文章主要介紹了SpringBoot中@ConfigurationProperties注解實(shí)現(xiàn)配置綁定的三種方法,文章內(nèi)容介紹詳細(xì)需要的小伙伴可以參考一下2022-04-04Java之SSM中bean相關(guān)知識(shí)匯總案例講解
這篇文章主要介紹了Java之SSM中bean相關(guān)知識(shí)匯總案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07IDEA 2020.1 搜索不到Chinese (Simplified) Language
小編在安裝中文插件時(shí)遇到IDEA 2020.1 搜索不到Chinese ​(Simplified)​ Language Pack EAP,無法安裝的問題,本文給大家分享我的解決方法,感興趣的朋友一起看看吧2020-04-04