java - JDK8的CompletableFuture使用問題
問題描述
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> { System.out.println('enter into completableFuture()'); try {TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace(); } System.out.println('start to out of completableFuture()'); return 'a';});System.out.println('do something else');cf1.thenApply(v -> v + ' b').thenAcceptAsync(v ->System.out.println(v));System.out.println('finalize...');//注釋最后一行,無法得到預(yù)期結(jié)果//TimeUnit.SECONDS.sleep(10);
得到引結(jié)果為:
do something elseenter into completableFuture()finalize...start to out of completableFuture()a b
以上代碼如果注釋掉最后一行,無法得到預(yù)期結(jié)果。
為什么一定要顯式的讓程序sleep10秒呢?
問題解答
回答1:見CompletableFuture.supplyAsync的javadoc:
Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.
而ForkJoinPool.commonPool()的javadoc:
Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown or shutdownNow. However this pool and any ongoing processing are automatically terminated upon program System.exit. Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.
如果你把最后的sleep改成ForkJoinPool.commonPool().awaitQuiescence(2, TimeUnit.SECONDS);也能達(dá)到你預(yù)期結(jié)果
回答2:搜索一下:守護(hù)線程當(dāng)線程中只剩下守護(hù)線程時(shí)JVM就會(huì)退出,反之還有任意一個(gè)用戶線程在,JVM都不會(huì)退出。我們可以猜測CompletableFuture.supplyAsync啟動(dòng)了一個(gè)守護(hù)線程,實(shí)際上CompletableFuture內(nèi)部默認(rèn)使用ForkJoinPool,該線程池初始化一個(gè)線程工廠類:
defaultForkJoinWorkerThreadFactory = new DefaultForkJoinWorkerThreadFactory();
查看他的的實(shí)現(xiàn),每次都是創(chuàng)建守護(hù)進(jìn)程。至于為什么一定要主線程sleep就很好理解。
相關(guān)文章:
1. node.js - nodejs+express+vue2. python - 如何把152753這個(gè)字符串轉(zhuǎn)變成時(shí)間格式15:27:533. python對8000行csv添加列4. javascript - onclick事件點(diǎn)擊不起作用5. python 字符串匹配問題6. DADB.class.php文件的代碼怎么寫7. 使用mysql命令行連接遠(yuǎn)程數(shù)據(jù)庫host跳轉(zhuǎn)8. javascript - 如何獲取未來元素的父元素在頁面中所有相同元素中是第幾個(gè)?9. javascript - 我的站點(diǎn)貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?10. 數(shù)據(jù)庫 - Mysql的存儲過程真的是個(gè)坑!求助下面的存儲過程哪里錯(cuò)啦,實(shí)在是找不到哪里的問題了。

網(wǎng)公網(wǎng)安備