java线程池处理多并发,所有进程执行完后再统一处理结果
线程池配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author
* @date 2020/2/21 11:47
* @description 线程池配置类
*/
@EnableAsync
@Configuration
public class ExecutorConfig {
@Value("${executor.size.core}")
private Integer core = 10;
@Value("${executor.size.max}")
private Integer max = 20;
@Value("${executor.size.queue}")
private Integer queue = 8;
@Value("${executor.keepalive.time}")
private Integer keepalive = 60;
@Bean
public ThreadPoolTaskExecutor brianThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(core);
//最大线程数
executor.setMaxPoolSize(max);
//队列中最大的数
executor.setQueueCapacity(queue);
//线程名称前缀
executor.setThreadNamePrefix("brianThreadPool_");
//rejectionPolicy:当pool已经达到max的时候,如何处理新任务
//callerRuns:不在新线程中执行任务,而是由调用者所在的线程来执行
//对拒绝task的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//线程空闲后最大的存活时间
executor.setKeepAliveSeconds(keepalive);
//初始化加载
executor.initialize();
return executor;
}
}
多线程并行demo
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* 线程处理
*
* @author:
* @qq: 1055182394
* @date: 2019/6/25 9:21
*/
@Service
@Slf4j
public class TestExecutorServiceImpl {
@Resource(name = "brianThreadPool")
private ThreadPoolTaskExecutor executor;
//定义全部变量,以免在用作定时任务时上一次未执行完成,下一次已经开始
private static boolean isRunning = false;
public R queryAllInfoSystem() {
if (isRunning == false) {
isRunning = true;
//用于保存网站监测结果
List resultList = new ArrayList();
//查找所有网站
List infoSystemDOS = new ArrayList<>();
//同步辅助类需要通过这个类来控制所有的线程都执行完成;
CountDownLatch countDownLatch = new CountDownLatch(infoSystemDOS.size());
if (infoSystemDOS != null && infoSystemDOS.size() > 0) {
for (int i = 0; i < infoSystemDOS.size(); i++) {
final int j = i;
executor.execute(new Runnable() {
@Override
public void run() {
try {
//监测网站连通性
InfoSystemDO infoSystemDO = infoSystemDOS.get(j);
//检测代码
//...
//结果保存到结果list
resultList.add(infoSystemDO);
System.out.println(Thread.currentThread().getName() + "---" + j);
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown(); //这个不管是否异常都需要数量减,否则会被堵塞无法结束
}
}
});
}
}
try {
countDownLatch.await(); //保证之前的所有的线程都执行完成,才会走下面的;
} catch (Exception e) {
log.error("阻塞异常");
}
}
//拿到所有的网站监测结果,统一处理
//resultList
//轮询resultList更新或保存数据库等
isRunning = false;
return R.ok();
}
}