← 中文资源

简体中文版本

Gatherers.mapConcurrent 并发映射

mapConcurrent 用最多 N 个虚拟线程并发执行映射,输出仍按 encounter order 排列;映射抛异常会以 RuntimeException 重抛并取消其余任务。

阅读英文原文

实现说明

整个示例围绕类 ConcurrentMapGatherer、Probe和函数 main组织。 stream 管道把“做什么”(变换)与“何时做”(终端 collect)分开。

使用要点

  • 跑完文件,输出里会留下标记——ordered:。

常见问题

运行「Gatherers.mapConcurrent 并发映射」会打印什么?

运行文件本身,ordered: 这些前缀各对应一段演示逻辑。

核心语句

Thread.currentThread().interrupt();
return p.id() + "@" + p.ms();
Thread.sleep(p.ms());

代码示例

import java.util.List;
import java.util.stream.Gatherers;

public class ConcurrentMapGatherer {

    record Probe(String id, int ms) {}

    public static void main(String[] args) {
        List<Probe> probes = List.of(
                new Probe("a", 30), new Probe("b", 10),
                new Probe("c", 20), new Probe("d", 5));

        // mapConcurrent:最多 3 个虚拟线程并发跑,输出仍保持 encounter order
        List<String> results = probes.stream()
                .gather(Gatherers.mapConcurrent(3, p -> {
                    try {
                        Thread.sleep(p.ms());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    return p.id() + "@" + p.ms();
                }))
                .toList();

        System.out.println(results);
        System.out.println("ordered: " + results.equals(List.of("a@30", "b@10", "c@20", "d@5")));
    }
}