在工作中经常会遇到一个业务操作要处理成千上万的数据,耗时非常严重,性能严重不达标,这个时候就会想到采用多线程来执行业务来提高执行效率,在该背景下本人写了一个可以直接套用业务的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

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

被折叠的 条评论
为什么被折叠?



