← 中文资源

简体中文版本

thenApply 与 thenApplyAsync 的线程选择

未完成的 future 上 thenApplyAsync 把阶段钉到指定线程池执行;已完成的 future 上 thenApply 在当前调用线程同步运行——阶段在哪个线程跑,代码里写得明明白白。

阅读英文原文

实现说明

thenApply 与 thenApplyAsync 的线程选择以类 ThreadChoice和函数 main为骨架。

使用要点

  • 跑完文件,输出里会留下标记——async stage on:、sync stage on:。

常见问题

运行「thenApply 与 thenApplyAsync 的线程选择」会打印什么?

运行文件本身,async stage on:、sync stage on: 这些前缀各对应一段演示逻辑。

核心语句

ExecutorService pool = Executors.newSingleThreadExecutor(
        r -> new Thread(r, "pool-worker"));
return v.toUpperCase();
return v + "!";

代码示例

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadChoice {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor(
                r -> new Thread(r, "pool-worker"));

        // 1) 未完成的 future + thenApplyAsync(pool):阶段被钉到指定池线程执行
        CompletableFuture<String> async = CompletableFuture
                .supplyAsync(() -> "payload", pool)
                .thenApplyAsync(v -> {
                    System.out.println("async stage on: " + Thread.currentThread().getName());
                    return v.toUpperCase();
                }, pool);
        String value = async.join();
        System.out.println(value);

        // 2) 已完成的 future + thenApply:结果就绪,当前调用线程立即同步执行
        String synced = async.thenApply(v -> {
            System.out.println("sync stage on:  " + Thread.currentThread().getName());
            return v + "!";
        }).join();
        System.out.println(synced);

        pool.shutdown();
    }
}