Spring boot多線程配置方法
更新時間:2017年10月30日 14:07:06 作者:瘦魚
這篇文章主要為大家詳細介紹了Spring boot多線程配置方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Spring boot多線程配置的具體代碼,供大家參考,具體內(nèi)容如下
1、配置線程配置類
package test; import java.util.concurrent.Executor; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration @ComponentScan("test") @EnableAsync // 線程配置類 public class AsyncTaskConfig implements AsyncConfigurer { // ThredPoolTaskExcutor的處理流程 // 當池子大小小于corePoolSize,就新建線程,并處理請求 // 當池子大小等于corePoolSize,把請求放入workQueue中,池子里的空閑線程就去workQueue中取任務并處理 // 當workQueue放不下任務時,就新建線程入池,并處理請求,如果池子大小撐到了maximumPoolSize,就用RejectedExecutionHandler來做拒絕處理 // 當池子的線程數(shù)大于corePoolSize時,多余的線程會等待keepAliveTime長時間,如果無請求可處理就自行銷毀 @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5);// 最小線程數(shù) taskExecutor.setMaxPoolSize(10);// 最大線程數(shù) taskExecutor.setQueueCapacity(25);// 等待隊列 taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
2、定義線程執(zhí)行任務類
package test; import java.util.Random; import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; @Service // 線程執(zhí)行任務類 public class AsyncTaskService { Random random = new Random();// 默認構(gòu)造方法 @Async // 表明是異步方法 // 無返回值 public void executeAsyncTask(Integer i) { System.out.println("執(zhí)行異步任務:" + i); } /** * 異常調(diào)用返回Future * * @param i * @return * @throws InterruptedException */ @Async public Future<String> asyncInvokeReturnFuture(int i) throws InterruptedException { System.out.println("input is " + i); Thread.sleep(1000 * random.nextInt(i)); Future<String> future = new AsyncResult<String>("success:" + i);// Future接收返回值,這里是String類型,可以指明其他類型 return future; } }
3、調(diào)用
package test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.task.TaskRejectedException; public class Application { public static void main(String[] args) throws InterruptedException, ExecutionException { // testVoid(); testReturn(); } // 測試無返回結(jié)果 private static void testVoid() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); // 創(chuàng)建了20個線程 for (int i = 1; i <= 20; i++) { asyncTaskService.executeAsyncTask(i); } context.close(); } // 測試有返回結(jié)果 private static void testReturn() throws InterruptedException, ExecutionException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); List<Future<String>> lstFuture = new ArrayList<Future<String>>();// 存放所有的線程,用于獲取結(jié)果 // 創(chuàng)建100個線程 for (int i = 1; i <= 100; i++) { while (true) { try { // 線程池超過最大線程數(shù)時,會拋出TaskRejectedException,則等待1s,直到不拋出異常為止 Future<String> future = asyncTaskService.asyncInvokeReturnFuture(i); lstFuture.add(future); break; } catch (TaskRejectedException e) { System.out.println("線程池滿,等待1S。"); Thread.sleep(1000); } } } // 獲取值。get是阻塞式,等待當前線程完成才返回值 for (Future<String> future : lstFuture) { System.out.println(future.get()); } context.close(); } }
maven配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestAysc</groupId> <artifactId>TestAysc</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <version>1.5.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.10.RELEASE</version> </dependency> </dependencies> </project>
結(jié)果展示:
1、無返回結(jié)果
2、有返回結(jié)果
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Idea SpringBoot搭建SpringCloud的準備工作(推薦)
這篇文章主要介紹了Idea SpringBoot搭建SpringCloud的準備工作(推薦),本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10SpringBoot項目使用yml文件鏈接數(shù)據(jù)庫異常問題解決方案
在使用SpringBoot時,利用yml進行數(shù)據(jù)庫連接配置需小心數(shù)據(jù)類型區(qū)分,如果用戶名或密碼是數(shù)字,必須用雙引號包裹以識別為字符串,避免連接錯誤,特殊字符密碼也應用引號包裹2024-10-10SpringMVC實現(xiàn)參數(shù)校驗配置方法
這篇文章主要介紹了SpringMVC實現(xiàn)參數(shù)校驗的配置方式,Spring MVC會拋出MethodArgumentNotValidException異常,并將錯誤信息綁定到相應的字段上,感興趣的朋友跟隨小編一起看看吧2024-03-03java實現(xiàn)給圖片加鋪滿的網(wǎng)格式文字水印
這篇文章主要給大家介紹了關(guān)于java實現(xiàn)給圖片加鋪滿的網(wǎng)格式文字水印的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01spring 自動注入AutowiredAnnotationBeanPostProcessor源碼解析
這篇文章主要介紹了spring自動注入AutowiredAnnotationBeanPostProcessor源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03