为什么有一个尚未完成的完成阶段,主线程不会终止?

问题描述 投票:0回答:1

这是我的简单代码:

public class Main4 {
    public static void main(String[] args) {
        System.out.println("Hello from thread: "+Thread.currentThread().getName());
        new Game().run();
        System.out.println("I am dying ... ");
    }

    static class Game {
        public void run() {
            value();
        }

        private int value() {
            int number = 0;
            CompletionStage<Void> c = calculate().thenApply(i -> i + 3).thenAccept(i -> System.out.println("I am done, and my value is " + i));
            return number;
        }

        private CompletionStage<Integer> calculate() {
            CompletionStage<Integer> completionStage = new CompletableFuture<>();
            Executors.newCachedThreadPool().submit(() -> {
                System.out.println("I am in the thread: " + Thread.currentThread().getName());
                try {
                    Thread.sleep(50000);
                    ((CompletableFuture<Integer>) completionStage).complete(3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;

            });
            return completionStage;
        }
    }
}

执行的输出是:

Hello from thread: main
I am in the thread: pool-1-thread-1
I am dying ... 

但是问题是:主线程不会立即终止,而是等待50000毫秒。这是我的问题。我知道它应该终止,因为没有更多的事情可以执行。

[最初,我认为原因是在主线程中执行了“ sleep”,这就是为什么我打印线程名称的原因,它们是两个不同的线程。

感谢您的帮助。

java completable-future completion-stage
1个回答
0
投票

默认情况下,您使用的线程池提供非守护线程。因此,程序必须在或终止之前等待生成线程

© www.soinside.com 2019 - 2024. All rights reserved.