线程池处理数据



            org.projectlombok
            lombok
            true


    cn.hutool
    hutool-all
    5.7.22

package com.example.demo.test.thread;

import cn.hutool.core.collection.CollectionUtil;
import com.example.demo.test.proxy.entity.StudentImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 

* *

* * @author: GoslingWu * @date: 2022-03-21 */ @Slf4j public class ThreadMain { static List list = CollectionUtil.newArrayList(); public static void main(String[] args) throws ExecutionException, InterruptedException { initData(); //每个线程处理的数据 Integer threadHandleDataNum = 30; Integer threadSize = getThreadSize(threadHandleDataNum); ExecutorService executorService = Executors.newFixedThreadPool(threadSize); for (int i = 0; i < threadSize; i++) { int threadIndex = i; executorService.execute(() -> { //每个线程处理的初始下标 int index = threadIndex * threadHandleDataNum; for (int j = 0; j < threadHandleDataNum; j++) { if (list.size() <= index) { return; } StudentImpl student = list.get(index); student.name = "GosingWu" + "第" + index + "次处理!"; log.info("第{}次处理!", index + 1); index += 1; } }); } executorService.shutdown(); } private static Integer getThreadSize(Integer threadHandleDataNum) { double count = list.size() / Double.valueOf(threadHandleDataNum); if (count > (int) count) { count++; } return (int) count; } private static void initData() { List collect = IntStream.range(1, 101).mapToObj(value -> { StudentImpl student = new StudentImpl(); student.id = Long.valueOf(value); student.age = value + 20; student.name = "我是GoslingWu!"; return student; }).peek(student -> log.info(student.id + ":" + student.name)) .collect(Collectors.toList()); list = collect; } }