Java项目开发过程中,常常与多线程打交道,于是我把多线程提取出来成为工具,具体介绍如下。
使用:引入依赖
<dependency>
<groupId>com.evil</groupId>
<artifactId>common-utils</artifactId>
<version>版本</version>
</dependency>
步骤
step0:注入ThreadPoolConfig
@Autowired
protected ThreadPoolConfig threadPoolConfig;
step1:项目使用
List<T> result = threadPoolConfig.doTask(childTaskList);
备注:配置文件参数
evil:
#线程池配置 zoom-common-threadpool.jar
thread.pool:
#执行并行任务时,等待多久时间超时
timeOut: 60
#队列大小
queueSize: 1000
#核心线程大小
coreThreadNum: 100
#线程池线程大小
maxPoolSize: 200
#并行执行每组大小
groupSize: 20
/**
* @author 阿巳
*/
@ConfigurationProperties(prefix = "evil.thread.pool")
@Data
@Validated
@Configuration
public class ThreadPoolProperties {
/**
* 执行并行任务时,等待多久时间超时 不能为空
*/
@NotNull
private Integer timeOut;
/**
* 队列大小
*/
@NotNull
private Integer queueSize;
/**
* 核心线程大小
*/
@NotNull
private Integer coreThreadNum;
/**
* 线程池线程大小
*/
@NotNull
private Integer maxPoolSize;
/**
* 并行执行每组大小 默认20
*/
private Integer groupSize = 20;
}
/**
* @author 阿巳
*/
@Configuration
@Data
public class ThreadPoolConfig {
private ThreadPoolProperties threadPoolProperties;
private ThreadPoolExecutor executor;
private ThreadPoolExecutor executorChild;
public ThreadPoolConfig(ThreadPoolProperties poolProperties){
this.threadPoolProperties = poolProperties;
this.executor = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-service"
,poolProperties.getQueueSize()
,poolProperties.getCoreThreadNum()
,poolProperties.getMaxPoolSize());
this.executorChild = ExecutorFactory.getInstance().getThreadPoolExecutor("ThreadPoolConfig-child"
,poolProperties.getQueueSize()
,poolProperties.getCoreThreadNum()
,poolProperties.getMaxPoolSize());
}
/**
* 并发执行任务
* @param taskList 任务列表
* @param executors
* @param <T>
* @return 返回参数
*/
public <T> List<T> doTask(List<Callable<T>> taskList ,ThreadPoolExecutor... executors){
if (taskList == null || taskList.isEmpty()){
return null;
}
List<T> result = new ArrayList<>();
List<Future<T>> futureList = null;
try {
if (executor.getQueue().size() >= threadPoolProperties.getQueueSize()){
throw new RuntimeException("queue size bigger than 100, now size is " + executor.getQueue().size());
}
if (executors != null && executors.length > 0 && executors[0] != null){
futureList = executors[0].invokeAll(taskList);
}else {
futureList = executor.invokeAll(taskList,threadPoolProperties.getTimeOut(), TimeUnit.SECONDS);
}
}catch (InterruptedException e){
e.printStackTrace();
}
doFutureList(result, futureList);
return result;
}
private <T> void doFutureList(List<T> result, List<Future<T>> futureList) {
if (futureList != null){
for (Future<T> future : futureList) {
try {
result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
}
具体项目地址:https://gitee.com/chen_three/common-utils.git ,欢迎各位指导和star!