公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。
<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.22</version>
</dependency>
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;

/**
 * <p>
 *
 * </p>
 *
 * @author: GoslingWu
 * @date: 2022-03-21
 */
@Slf4j
public class ThreadMain {

    static List<StudentImpl> 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<StudentImpl> 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;
    }

}

posted on 2022-03-21 11:53  公众号/架构师与哈苏  阅读(63)  评论(0编辑  收藏  举报