當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Springboot 多线程的使用
生活随笔
收集整理的這篇文章主要介紹了
Springboot 多线程的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
直接上代碼
線程配置類
package zengmg.nbpi.com.thread;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.Executor;/*** @Auther 松門一枝花* @Date 2020/5/28*/ @Configuration @EnableAsync // 啟用異步任務 public class AsyncConfiguration {// 聲明一個線程池(并指定線程池的名字)@Bean("nbpiTaskExecutor")public Executor asyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//核心線程數:線程池創建時候初始化的線程數executor.setCorePoolSize(5);//最大線程數:線程池最大的線程數,只有在緩沖隊列滿了之后才會申請超過核心線程數的線程executor.setMaxPoolSize(500);//允許線程的空閑時間60秒:當超過了核心線程出之外的線程在空閑時間到達之后會被銷毀executor.setKeepAliveSeconds(60);//線程池名的前綴:設置好了之后可以方便我們定位處理任務所在的線程池executor.setThreadNamePrefix("DailyAsync-");executor.initialize();return executor;} }服務類
package zengmg.nbpi.com.thread;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service;/*** @Auther 松門一枝花* @Date 2020/5/28*/ @Service public class CustomMultiThreadingService {private static final Logger logger = LoggerFactory.getLogger(CustomMultiThreadingService.class);/*如何讓異步調用的執行任務使用這個線程池中的資源來運行呢?方法非常簡單,我們只需要在@Async注解中指定線程池名即可*/@Async("nbpiTaskExecutor")public void executeAysncTask(Integer i) throws InterruptedException {logger.info("CustomMultiThreadingService ==> executeAysncTask1 method: 執行異步任務{} ", i);Thread.sleep(500L);}}控制類
package zengmg.nbpi.com.thread;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;/*** @Auther 松門一枝花* @Date 2020/5/28*/ @Controller @RequestMapping(value="/multithreading") public class CustomMultiThreadingController {@Autowiredprivate CustomMultiThreadingService customMultiThreadingService;@ResponseBody@RequestMapping("/dotask")public String doTask() {try {for (int i=0;i<100000;i++){customMultiThreadingService.executeAysncTask(i);}} catch (InterruptedException e) {e.printStackTrace();}return "success";}}運行效果
?
異步方法和調用方法一定要寫在不同的類中?,如果寫在一個類中,是沒有效果的!
?
?
?
總結
以上是生活随笔為你收集整理的Springboot 多线程的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 方便微信公众号等手机网页调试插件erud
- 下一篇: 区分 JSON 字符串与JSON对象