下面是一个可能的解决方案:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<String> dataList = new ArrayList<>(); // 待处理的数据列表
        for (int i = 1; i <= 20; i++) {
            dataList.add("Data " + i);
        }

        int poolSize = 5; // 线程池大小
        ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
        List<Future<List<String>>> resultList = new ArrayList<>(); // 结果列表

        // 将数据列表平均分配给线程池
        int batchSize = (int) Math.ceil((double) dataList.size() / poolSize);
        for (int i = 0; i < poolSize; i++) {
            int fromIndex = i * batchSize;
            int toIndex = Math.min((i + 1) * batchSize, dataList.size());
            List<String> batchList = dataList.subList(fromIndex, toIndex);

            Callable<List<String>> task = new BatchProcessor(batchList);
            Future<List<String>> future = executorService.submit(task);
            resultList.add(future);
        }

        executorService.shutdown(); // 关闭线程池(等待所有任务完成)

        List<String> finalResult = new ArrayList<>();
        for (Future<List<String>> future : resultList) {
            List<String> batchResult = future.get();
            finalResult.addAll(batchResult);
        }

        System.out.println("Final result: " + finalResult);
    }

    private static class BatchProcessor implements Callable<List<String>> {
        private final List<String> batchList;

        public BatchProcessor(List<String> batchList) {
            this.batchList = batchList;
        }

        @Override
        public List<String> call() throws Exception {
            // 处理数据列表并返回结果
            List<String> result = new ArrayList<>();
            for (String data : batchList) {
                String processedData = "Processed " + data;
                result.add(processedData);
            }
            return result;
        }
    }
}

这个程序创建了一个大小为5的固定线程池,将待处理的数据列表平均分配给线程池中的5个线程,并将每个线程的处理结果保存在一个 Future 对象中。最后,程序等待所有任务完成并将结果按顺序汇总成一个列表。

注意,为了避免并发修改异常,程序使用了 List.subList() 方法将待处理的数据列表分成多个子列表,并将每个子列表传递给线程池中的单个线程进行处理。这样做的好处是可以避免不必要的同步开销。

java ThreadPoolExecutor 创建5个线程池每个线程池平均分配list里面的数据并且得到结果按顺序汇总成一个list

原文地址: http://www.cveoy.top/t/topic/bVVO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录