国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

java - JDK8的CompletableFuture使用問題

瀏覽:122日期:2023-10-31 13:05:02

問題描述

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...');//注釋最后一行,無法得到預期結果//TimeUnit.SECONDS.sleep(10);

得到引結果為:

do something elseenter into completableFuture()finalize...start to out of completableFuture()a b

以上代碼如果注釋掉最后一行,無法得到預期結果。

為什么一定要顯式的讓程序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);也能達到你預期結果

回答2:

搜索一下:守護線程當線程中只剩下守護線程時JVM就會退出,反之還有任意一個用戶線程在,JVM都不會退出。我們可以猜測CompletableFuture.supplyAsync啟動了一個守護線程,實際上CompletableFuture內部默認使用ForkJoinPool,該線程池初始化一個線程工廠類:

defaultForkJoinWorkerThreadFactory = new DefaultForkJoinWorkerThreadFactory();

查看他的的實現,每次都是創建守護進程。至于為什么一定要主線程sleep就很好理解。

標簽: java
相關文章:
主站蜘蛛池模板: 新巴尔虎右旗| 海林市| 莲花县| 陆河县| 宜城市| 齐河县| 克拉玛依市| 洛隆县| 怀远县| 依兰县| 清河县| 潼关县| 扎囊县| 顺平县| 临夏县| 和硕县| 耒阳市| 绵竹市| 普安县| 公安县| 喀什市| 浮山县| 乐陵市| 德安县| 车险| 汪清县| 沙河市| 晋城| 公安县| 曲沃县| 博爱县| 宝鸡市| 巢湖市| 陆川县| 双柏县| 宜城市| 海安县| 施甸县| 临城县| 夏邑县| 弋阳县|