一、配置线程配置类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