Spring 多线程
Spring 通过任务执行器TaskExecutor来实现多线程和并发编程。
使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。
使用@EnableAsync开启对一处任务的支持,并通过在实际执行的Bean方法中使用@Asycn注解声明其实一个异步任务。
例:
1. 创建Spring 任务执行器
package com.cz.thread; 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; import java.util.concurrent.Executor; /** * Created by Administrator on 2017/5/7. */ @Configuration @ComponentScan("com.cz.thread") @EnableAsync // 开启异步任务支持 public class TaskExecutorConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(25); taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
2. 任务处理类
package com.cz.thread; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * Created by Administrator on 2017/5/7. */ @Service public class AsyncTaskService { @Async public void executeAsyncTask(Integer i){ System.out.println("执行异步任务:" + i); } @Async public void executeAsyncTaskPlus(Integer i){ System.out.println("执行异步任务+1:" + (i+1)); } }
3. 测试
package com.cz.thread; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by Administrator on 2017/5/7. */ public class TestSpringSyncTask { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); for(int i=0; i<10; i++){ // asyncTaskService.executeAsyncTask(i); asyncTaskService.executeAsyncTaskPlus(i); } context.close(); } }
4. 运行结果