多线程
Spring 通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync开启对异步的支持,并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务。
示例
首先配置类
package com.cn.sola.config;
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.cn.sola.service")
@EnableAsync//利用此注解开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
//配置类实现AsyncConfigurer 接口 并重写getAsyncExecutor方法并返回一个ThreadPoolTaskExecutor
//这样我们就获得了一个基于线程池的TaskExecutor
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return null;
}
}
任务执行类
package com.cn.sola.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async//该注表明该方法是个异步方法,如果注解在类级别,则表名该类所有的方法都是异步方
//而这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor
public void excuteAsyncTask(Integer i){
System.out.println("执行异步任务"+i);
}
@Async
public void excuteAsyncTaskPlus(Integer i){
System.out.println("执行异步任务+1:"+(i+1));
}
}
运行
package com.cn.sola;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.cn.sola.config.TaskExecutorConfig;
import com.cn.sola.service.AsyncTaskService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootShiZhanApplicationTests {
@Test
public void contextLoads() {