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