????? 以下实例:
class="配置类TaskExecutorConfig" name="code">package com.zgw.taskexecutor; 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("com.zgw.taskexecutor") @EnableAsync //开启对异步任务的支持 public class TaskExecutorConfig implements AsyncConfigurer { /** * 通过实现AsyncConfigurer接口,重写getAsyncExecutor()方法, * 返回一个ThreadPoolTaskExecutor对象,这样实现一个基于线程池 * TaskExecutor */ @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(10); taskExecutor.setMaxPoolSize(20); taskExecutor.setQueueCapacity(25); taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
?????
Service" name="code">package com.zgw.taskexecutor; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncTaskService { @Async //声明是一个异步方法 public void executeAsyncTaskOne(int i){ System.out.println("执行异步任务: "+i); } @Async public void executeAsyncTaskTwo(int i){ System.out.println("执行异步任务加1操作:"+(i+1)); } }
?
?
3.运行
package com.zgw.taskexecutor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestExecutor { public static void main(String[] args) { //使用AnnotationConfigApplicationContext作为spring容器, //接收输入一个配置类作为参数 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class); //获得声明配置的AsyncTaskService的Bean AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); for(int i =0 ;i<20;i++){ asyncTaskService.executeAsyncTaskOne(i); asyncTaskService.executeAsyncTaskTwo(i);; } context.close(); } }
?
3.运行
?
package com.zgw.taskexecutor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestExecutor { public static void main(String[] args) { //使用AnnotationConfigApplicationContext作为spring容器, //接收输入一个配置类作为参数 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class); //获得声明配置的AsyncTaskService的Bean AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); for(int i =0 ;i<20;i++){ asyncTaskService.executeAsyncTaskOne(i); asyncTaskService.executeAsyncTaskTwo(i);; } context.close(); } }
?
? 运行结果如下:
?
?
?结果是并发执行而不是顺序执行的。
?
????