Spring boot多線程

一、配置線程配置類java

 1 package test;
 2 
 3 import java.util.concurrent.Executor;
 4 
 5 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
 6 import org.springframework.context.annotation.ComponentScan;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.scheduling.annotation.AsyncConfigurer;
 9 import org.springframework.scheduling.annotation.EnableAsync;
10 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
11 
12 @Configuration
13 @ComponentScan("test")
14 @EnableAsync
15 // 線程配置類
16 public class AsyncTaskConfig implements AsyncConfigurer {
17 
18     // ThredPoolTaskExcutor的處理流程
19     // 當池子大小小於corePoolSize,就新建線程,並處理請求
20     // 當池子大小等於corePoolSize,把請求放入workQueue中,池子裏的空閒線程就去workQueue中取任務並處理
21     // 當workQueue放不下任務時,就新建線程入池,並處理請求,若是池子大小撐到了maximumPoolSize,就用RejectedExecutionHandler來作拒絕處理
22     // 當池子的線程數大於corePoolSize時,多餘的線程會等待keepAliveTime長時間,若是無請求可處理就自行銷燬
23 
24     @Override
25     public Executor getAsyncExecutor() {
26         ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
27         taskExecutor.setCorePoolSize(5);// 最小線程數
28         taskExecutor.setMaxPoolSize(10);// 最大線程數
29         taskExecutor.setQueueCapacity(25);// 等待隊列
30 
31         taskExecutor.initialize();
32 
33         return taskExecutor;
34     }
35 
36     @Override
37     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
38         return null;
39     }
40 }

二、定義線程執行任務類spring

 1 package test;
 2 
 3 import java.util.Random;
 4 import java.util.concurrent.Future;
 5 
 6 import org.springframework.scheduling.annotation.Async;
 7 import org.springframework.scheduling.annotation.AsyncResult;
 8 import org.springframework.stereotype.Service;
 9 
10 @Service
11 // 線程執行任務類
12 public class AsyncTaskService {
13 
14     Random random = new Random();// 默認構造方法
15 
16     @Async
17     // 代表是異步方法
18     // 無返回值
19     public void executeAsyncTask(Integer i) {
20         System.out.println("執行異步任務:" + i);
21     }
22 
23     /**
24      * 異常調用返回Future
25      * 
26      * @param i
27      * @return
28      * @throws InterruptedException
29      */
30     @Async
31     public Future<String> asyncInvokeReturnFuture(int i) throws InterruptedException {
32         System.out.println("input is " + i);
33         Thread.sleep(1000 * random.nextInt(i));
34 
35         Future<String> future = new AsyncResult<String>("success:" + i);// Future接收返回值,這裏是String類型,能夠指明其餘類型
36 
37         return future;
38     }
39 }

三、調用apache

 1 package test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.concurrent.ExecutionException;
 6 import java.util.concurrent.Future;
 7 
 8 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 9 import org.springframework.core.task.TaskRejectedException;
10 
11 public class Application {
12 
13     public static void main(String[] args) throws InterruptedException, ExecutionException {
14         // testVoid();
15 
16         testReturn();
17     }
18 
19     // 測試無返回結果
20     private static void testVoid() {
21         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
22         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
23 
24         // 建立了20個線程
25         for (int i = 1; i <= 20; i++) {
26             asyncTaskService.executeAsyncTask(i);
27         }
28 
29         context.close();
30     }
31 
32     // 測試有返回結果
33     private static void testReturn() throws InterruptedException, ExecutionException {
34         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
35         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
36 
37         List<Future<String>> lstFuture = new ArrayList<Future<String>>();// 存放全部的線程,用於獲取結果
38 
39         // 建立100個線程
40         for (int i = 1; i <= 100; i++) {
41             while (true) {
42                 try {
43                     // 線程池超過最大線程數時,會拋出TaskRejectedException,則等待1s,直到不拋出異常爲止
44                     Future<String> future = asyncTaskService.asyncInvokeReturnFuture(i);
45                     lstFuture.add(future);
46 
47                     break;
48                 } catch (TaskRejectedException e) {
49                     System.out.println("線程池滿,等待1S。");
50                     Thread.sleep(1000);
51                 }
52             }
53         }
54 
55         // 獲取值。get是阻塞式,等待當前線程完成才返回值
56         for (Future<String> future : lstFuture) {
57             System.out.println(future.get());
58         }
59 
60         context.close();
61     }
62 }

maven配置dom

 1 <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">
 2   <modelVersion>4.0.0</modelVersion>
 3   <groupId>TestAysc</groupId>
 4   <artifactId>TestAysc</artifactId>
 5   <version>0.0.1-SNAPSHOT</version>
 6   <dependencies>
 7       <dependency>
 8           <groupId>org.springframework.boot</groupId>
 9           <artifactId>spring-boot</artifactId>
10           <version>1.5.6.RELEASE</version>
11       </dependency>
12       <dependency>
13           <groupId>org.springframework</groupId>
14           <artifactId>spring-aop</artifactId>
15           <version>4.3.10.RELEASE</version>
16       </dependency>
17   </dependencies>
18 </project>

 結果展現:異步

一、無返回結果async

二、有返回結果maven

相關文章
相關標籤/搜索