1、查询数据列表
2、自定义线程池配置,类注解@Configuration
/**
* 自定义线程池
*/
@Bean(name = "executor")
public ExecutorService executorService(){
return new ThreadPoolExecutor(
5, // 核心线程数
10, // 最大线程数
60L, // 线程存活时间
TimeUnit.SECONDS, // 时间单位
new ArrayBlockingQueue<>(100), // 任务队列
new ThreadPoolExecutor.CallerRunsPolicy());
}
3、注入使用,获取bean
#例如
@Autowired
private ExecutorService executor;
4、定义执行线程thread类,注意有些内容线程不安全,需要在外面定义好传进来,以保证线程安全,同样线程里最好不要调用接口之类的,需要接口使用SpringBeanUtils.getBean(name)获取。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
/**
* xx业务多线程处理
*/
public class XXThread implements Runnable{
Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final CountDownLatch latch;
private final 传入业务参数或者对象 c;
public XXThread (参数或者对象 c, CountDownLatch countDownLatch) {
this.c= c;
this.latch = countDownLatch;
}
@Override
public void run() {
logger.info("当前执行线程:"+Thread.currentThread().getName());
try {
logger.info("是否进来了");
//业务
...........
}catch (Exception e){
e.printStackTrace();
}finally {
latch.countDown();
}
}
}
5、循环列表单独执行每个线程,之前前传入计数器
CountDownLatch latch = new CountDownLatch(list.size());
for(Object o:list){
ClassThread thread = new ClassThread(o,latch)
executor.execute(thread);
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
while (!executor.isTerminated()){
}
if (executor.isTerminated()){
logger.info("线程执行完成");
}