Java 意外的异步行为

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

我期待 Java 中出现意外行为(Java 17、Spring Boot 应用程序)。该方法用于测试,我直接从 main 方法调用它。

主线程不应该在 thenApply() 行被阻塞吗?为什么没有?

根据我的 Java 知识以及迄今为止我检查和研究的所有内容 thenApply() 应该是阻塞的,在我的情况下它的行为类似于 thenApplyAsync()

`       System.out.println("Main Thread: " + Thread.currentThread().getName());

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            var otherThread = Thread.currentThread().getName();
            System.out.println("Future Thread: " + otherThread);

            return otherThread;
        });

        System.out.println("Code before thenApply: " + Thread.currentThread().getName());
        var result = future.thenApply(res -> {
            System.out.println("Future Thread in Result: " + res);

            System.out.println("Then Apply Thread: " + Thread.currentThread().getName());

            return res;
        });

        System.out.println("Code after thenApply: " + Thread.currentThread().getName());

        try {
            var finalResult = result.get();
            System.out.println("Code after get: " + Thread.currentThread().getName());
            System.out.println("After get result:" + finalResult);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

Logs:
Main Thread: main
Code before thenApply: main
Code after thenApply: main
Future Thread: ForkJoinPool.commonPool-worker-1
Future Thread in Result: ForkJoinPool.commonPool-worker-1
Then Apply Thread: ForkJoinPool.commonPool-worker-1
Code after get: main
After get...ForkJoinPool.commonPool-worker-1`
java asynchronous completable-future java-threads
1个回答
0
投票
如果前一阶段已经完成(在您的情况下尚未完成),则

thenApply
可能会阻塞线程。 thenApplyAsync
保证不会阻塞当前线程,即使它已经完成。

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