SpringBoot多線程環(huán)境下,解決多個定時器沖突問題
閱讀本文大概需要 2.8 分鐘。
來自:blog.csdn.net/cssnnd/article/details/108328942
戰(zhàn)術(shù)分析:

使用場景 :
總的來說,實際開發(fā)中定時器需要解決多個定時器同時并發(fā)的問題,也要解決定時器之間的沖突問題
問題場景重現(xiàn) :


添加注解

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;
@Component
public?class?SchedulerTaskController?{
????private?Logger?logger=?LoggerFactory.getLogger(SchedulerTaskController.class);
????private?static?final?SimpleDateFormat?dateFormat=new?SimpleDateFormat("HH:mm:ss");
????private?int?count=0;
????@Scheduled(cron="*/6?*?*?*?*??")
????@Async("threadPoolTaskExecutor")
????public?void?process(){
????????logger.info("英文:this?is?scheduler?task?runing?"+(count++));
????}
????@Scheduled(fixedRate?=?6000)
????@Async("threadPoolTaskExecutor")
????public?void?currentTime(){
????????logger.info("中文:現(xiàn)在時間"+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;
/**使用多線程的時候,往往需要創(chuàng)建Thread類,或者實現(xiàn)Runnable接口,如果要使用到線程池,我們還需要來創(chuàng)建Executors,
?*?在使用spring中,已經(jīng)給我們做了很好的支持。只要要@EnableAsync就可以使用多線程
?*?通過spring給我們提供的ThreadPoolTaskExecutor就可以使用線程池。*/
//@Configuration?表示該類是一個配置類
@Configuration
@EnableAsync
//所有的定時任務(wù)都放在一個線程池中,定時任務(wù)啟動時使用不同都線程。
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;???//?允許線程空閑時間(單位:默認(rèn)為秒),十秒后就把線程關(guān)閉
????private?static?final?int?queueCapacity?=?200;???//?緩沖隊列數(shù)
????private?static?final?String?threadNamePrefix?=?"it-is-threaddemo-";?//?線程池名前綴
????@Bean("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;
????}
}


推薦閱讀:
SpringBoot + Redis:模擬 10w 人的秒殺搶單!
內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper、數(shù)據(jù)結(jié)構(gòu)、限流熔斷降級......等技術(shù)棧!
?戳閱讀原文領(lǐng)??!? ? ? ? ? ? ? ??? ??? ? ? ? ? ? ? ? ? ?朕已閱?
評論
圖片
表情

