SpringBoot多線程環(huán)境下,解決多個(gè)定時(shí)器沖突問題
作者:瓦坎達(dá)forever
來源:blog.csdn.net/cssnnd/article/details/108328942
戰(zhàn)術(shù)分析 :

具體代碼如下 :
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;public class SchedulerTaskController {private Logger logger= LoggerFactory.getLogger(SchedulerTaskController.class);private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");private int count=0;(cron="*/6 * * * * ?")("threadPoolTaskExecutor")public void process(){logger.info("英文:this is scheduler task runing "+(count++));}(fixedRate = 6000)("threadPoolTaskExecutor")public void currentTime(){logger.info("中文:現(xiàn)在時(shí)間"+dateFormat.format(new Date()));}}
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;/**使用多線程的時(shí)候,往往需要?jiǎng)?chuàng)建Thread類,或者實(shí)現(xiàn)Runnable接口,如果要使用到線程池,我們還需要來創(chuàng)建Executors,* 在使用spring中,已經(jīng)給我們做了很好的支持。只要要@EnableAsync就可以使用多線程* 通過spring給我們提供的ThreadPoolTaskExecutor就可以使用線程池。*///@Configuration 表示該類是一個(gè)配置類//所有的定時(shí)任務(wù)都放在一個(gè)線程池中,定時(shí)任務(wù)啟動(dòng)時(shí)使用不同都線程。public class TaskScheduleConfig {private static final int corePoolSize = 10; // 默認(rèn)線程數(shù)private static final int maxPoolSize = 100; // 最大線程數(shù)private static final int keepAliveTime = 10;// 允許線程空閑時(shí)間(單位:默認(rèn)為秒),十秒后就把線程關(guān)閉private static final int queueCapacity = 200;// 緩沖隊(duì)列數(shù)private static final String threadNamePrefix = "it-is-threaddemo-"; // 線程池名前綴("threadPoolTaskExecutor") // bean的名稱,默認(rèn)為首字母小寫的方法名public ThreadPoolTaskExecutor getDemoThread(){ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(corePoolSize);executor.setMaxPoolSize(maxPoolSize);executor.setQueueCapacity(keepAliveTime);executor.setKeepAliveSeconds(queueCapacity);executor.setThreadNamePrefix(threadNamePrefix);//線程池拒絕任務(wù)的處理策略executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//初始化executor.initialize();return executor;}}
然后我們可以很清晰地看到

感謝您的閱讀,也歡迎您發(fā)表關(guān)于這篇文章的任何建議,關(guān)注我,技術(shù)不迷茫!小編到你上高速。
正文結(jié)束
1.心態(tài)崩了!稅前2萬4,到手1萬4,年終獎(jiǎng)扣稅方式1月1日起施行~
2.深圳一普通中學(xué)老師工資單曝光,秒殺程序員,網(wǎng)友:敢問是哪個(gè)學(xué)校畢業(yè)的?
3.從零開始搭建創(chuàng)業(yè)公司后臺(tái)技術(shù)棧
5.清華大學(xué):2021 元宇宙研究報(bào)告!

評(píng)論
圖片
表情
