栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么CompletableFuture.supplyAsync成功连续随机执行几次?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么CompletableFuture.supplyAsync成功连续随机执行几次?

默认情况下

CompletableFuture
使用自己的 ForkJoinPool.commonPool()
(请参阅
CompletableFuture
实现)。并且该默认池仅创建
守护程序 线程,例如,如果它们仍然存在,它们将不会阻止主应用程序终止。

您有以下选择:

  1. 将所有内容收集

    CompletionStage
    到某个数组中,然后进行制作-这将确保在执行 join() 之后所有阶段都已完成
    java.util.concurrent.CompletableFuture#allOf()
    .toCompletableFuture().join()
    __

  2. 对您自己的仅包含 非守护程序 线程的线程池使用 * Async 操作,如以下示例所示: __

        public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newFixedThreadPool(10, r -> { Thread t = new Thread(r); t.setDaemon(false); // must be not daemon return t;        });        for (int i = 0; i < 100; i++) { final int a = i; // the operation must be Async with our thread pool CompletableFuture<Boolean> cf = CompletableFuture.supplyAsync(() -> doPost(a), pool); cf.thenRun(() -> System.out.printf("%s: Run_%s%n", Thread.currentThread().getName(), a));        }        pool.shutdown(); // without this the main application will be blocked forever    }    private static boolean doPost(int t) {        System.out.printf("%s: Post_%s%n", Thread.currentThread().getName(), t);        return true;    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453045.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号