一、創建線程池
@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);