您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

您有以下选择:

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

对您自己的仅包含 非守护程序 线程的线程池使用 * 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;
    }
其他 2022/1/1 18:21:40 有489人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶