您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在Spring boot中對(duì)多線程進(jìn)行配置,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
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的處理流程 // 當(dāng)池子大小小于corePoolSize,就新建線程,并處理請(qǐng)求 // 當(dāng)池子大小等于corePoolSize,把請(qǐng)求放入workQueue中,池子里的空閑線程就去workQueue中取任務(wù)并處理 // 當(dāng)workQueue放不下任務(wù)時(shí),就新建線程入池,并處理請(qǐng)求,如果池子大小撐到了maximumPoolSize,就用RejectedExecutionHandler來(lái)做拒絕處理 // 當(dāng)池子的線程數(shù)大于corePoolSize時(shí),多余的線程會(huì)等待keepAliveTime長(zhǎng)時(shí)間,如果無(wú)請(qǐng)求可處理就自行銷毀 @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5);// 最小線程數(shù) taskExecutor.setMaxPoolSize(10);// 最大線程數(shù) taskExecutor.setQueueCapacity(25);// 等待隊(duì)列 taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
2、定義線程執(zhí)行任務(wù)類
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í)行任務(wù)類 public class AsyncTaskService { Random random = new Random();// 默認(rèn)構(gòu)造方法 @Async // 表明是異步方法 // 無(wú)返回值 public void executeAsyncTask(Integer i) { System.out.println("執(zhí)行異步任務(wù):" + 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(); } // 測(cè)試無(wú)返回結(jié)果 private static void testVoid() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); // 創(chuàng)建了20個(gè)線程 for (int i = 1; i <= 20; i++) { asyncTaskService.executeAsyncTask(i); } context.close(); } // 測(cè)試有返回結(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個(gè)線程 for (int i = 1; i <= 100; i++) { while (true) { try { // 線程池超過(guò)最大線程數(shù)時(shí),會(huì)拋出TaskRejectedException,則等待1s,直到不拋出異常為止 Future<String> future = asyncTaskService.asyncInvokeReturnFuture(i); lstFuture.add(future); break; } catch (TaskRejectedException e) { System.out.println("線程池滿,等待1S。"); Thread.sleep(1000); } } } // 獲取值。get是阻塞式,等待當(dāng)前線程完成才返回值 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、無(wú)返回結(jié)果
2、有返回結(jié)果
關(guān)于怎么在Spring boot中對(duì)多線程進(jìn)行配置就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。