为什么不使用Java ExecutorService将元素添加到列表中?

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

以某种方式我的所有元素均未添加到列表中,这是我的代码:

List<Record> recordList = new ArrayList<>();
        batchList.forEach(batch -> {
            executor.submit(() -> {
                recordList.add(csvToJson(batch));
            });
        });
        log.info("recordList.size(): {}", recordList.size());

我的日志显示recordList.size(): 0csvToJson(batch)函数返回之前,我还打印了最终结果,它是有效的合法非空对象。

executor像这样初始化并传递到此方法中:

ExecutorService executor = Executors.newFixedThreadPool(10);

我的直觉是,我应该使用线程安全列表而不是ArrayList。

java concurrency threadpool executorservice threadpoolexecutor
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.