springboot 使用线程池处理多线程任务


一、创建线程池

@Configuration
@EnableAsync
public class SpringAsyncConfig {

@Bean("taskExecutor")
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 设置最大线程数
executor.setMaxPoolSize(20);
//配置队列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("xcc");
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//执行初始化
executor.initialize();
return executor;
}
}

二、创建使用线程池的server(网上有人说线程任务最好放到一个server里面不然会造成循环依赖。。。未验证)
public interface ThreadUtilsService {
/**
* 获取用户下的考勤记录
* @param wechatUser
*/
void setAttendance(WechatUser wechatUser, CountDownLatch countDownLatch);
}


@Service
public class ThreadUtilsServiceImpl implements ThreadUtilsService {
@Autowired
private AttendanceService attendanceService;

@Async("taskExecutor")
@Override
public void setAttendance(WechatUser wechatUser, CountDownLatch countDownLatch) {
List<Attendance> currentClockListByOpenId = attendanceService.getCurrentClockListByOpenId(wechatUser);
countDownLatch.countDown();
wechatUser.setAttendanceList(currentClockListByOpenId);
}
}


三、调用
threadUtilsService.setAttendance(record,countDownLatch);




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM