java - JDK8的CompletableFuture使用問(wèn)題
問(wèn)題描述
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...');//注釋最后一行,無(wú)法得到預(yù)期結(jié)果//TimeUnit.SECONDS.sleep(10);
得到引結(jié)果為:
do something elseenter into completableFuture()finalize...start to out of completableFuture()a b
以上代碼如果注釋掉最后一行,無(wú)法得到預(yù)期結(jié)果。
為什么一定要顯式的讓程序sleep10秒呢?
問(wèn)題解答
回答1:見(jiàn)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ì)退出。我們可以猜測(cè)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. python bottle跑起來(lái)以后,定時(shí)執(zhí)行的任務(wù)為什么每次都重復(fù)(多)執(zhí)行一次?2. javascript - vue2.0中,$refs對(duì)象為什么用駝峰的方式獲取不到屬性?3. javascript - vue2如何獲取v-model變量名4. javascript - 求幫助 , ATOM不顯示界面!!!!5. html5 - HTML代碼中的文字亂碼是怎么回事?6. python - 爬蟲(chóng)模擬登錄后,爬取csdn后臺(tái)文章列表遇到的問(wèn)題7. javascript - ios返回不執(zhí)行js怎么解決?8. javascript - 能否讓vue-cli的express修改express重啟服務(wù)9. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示10. mysql - 分庫(kù)分表、分區(qū)、讀寫(xiě)分離 這些都是用在什么場(chǎng)景下 ,會(huì)帶來(lái)哪些效率或者其他方面的好處
