多线程分批处理数据

文章介绍了如何使用Java实现多线程处理大量数据,通过创建自定义任务接口和线程池工具类,如ThreadPoolExecutor,来提高业务操作的执行效率。作者提供了一个实例,展示了如何按批次处理任务并记录每个英雄的战场耗时和战绩。

在工作中经常会遇到一个业务操作要处理成千上万的数据,耗时非常严重,性能严重不达标,这个时候就会想到采用多线程来执行业务来提高执行效率,在该背景下本人写了一个可以直接套用业务的demo,在此记录,以备随时用到来copy代码

首先定义个执行业务任务的接口

package AtomicTest;

/**
 * desc:
 * author:wangqiangac
 * date:2023/12/21 14:48
 */
public interface MyTask {

    <T> String  work(T www) throws Exception;
}

再创建一个构建线程池的工具类,代码如下,线程池参数可以根据自己需要做成可配置

package AtomicTest;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * desc:
 * author:wangqiangac
 * date:2023/12/21 17:17
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ThreadPoolBuilder {
    int corePoolSize;//设置ThreadPoolExecutor的核心池大小。默认值为1。此设置可以在运行时进行修改,例如通过JMX进行修改
    int maxPoolSize;//设置ThreadPoolExecutor的最大池大小。默认值为Integer。最大值。此设置可以在运行时进行修改,例如通过JMX进行修改。
    int queueCapacity;//设置ThreadPoolExecutor的BlockingQueue的容量。默认值为Integer。最大值
    int keepAliveSeconds;//设置ThreadPoolExecutor的保持活动秒数。默认值为60。
    String threadNamePrefix;//自定义名称前缀
    boolean prestartAllCoreThreads;//指定是否启动所有核心线程,使它们空闲等待工作。
    RejectedExecutionHandler rejectedExecutionHandler;
    public ThreadPoolBuilder setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
        return this;
    }

    public ThreadPoolBuilder setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
        return this;
    }

    public ThreadPoolBuilder setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
        return this;
    }

    public ThreadPoolBuilder setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSecond
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值