一、新建配置类
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
/**
* 核心线程数(默认线程数)
*/
private static final int CORE_POOL_SIZE = 10;
/**
* 最大线程数
*/
private static final int MAX_POOL_SIZE = 100;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int KEEP_ALIVE_TIME = 10;
/**
* 缓冲队列数
*/
private static final int QUEUE_CAPACITY = 200;
/**
* 线程池名前缀
*/
private static final String THREAD_NAME_PREFIX = "Async-Service-";
/**
* bean的名称,默认为首字母小写的方法名
*/
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(CORE_POOL_SIZE);
executor.setMaxPoolSize(MAX_POOL_SIZE);
executor.setQueueCapacity(QUEUE_CAPACITY);
executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
// 线程池对拒绝任务的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}
二、创建方法类
@Service
public class TaskService {
@Async("taskExecutor")
public synchronized void task(int i) throws InterruptedException {
System.out.println("线程 "+i+" 启动!");
// 模拟耗时
Thread.sleep(500);
System.out.println("线程 "+i+" 结束!");
}
}
三、启动类添加注解
@SpringBootApplication
@ComponentScan("com.example")
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
四、创建测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
TaskService taskService;
@Test
public void test() throws InterruptedException {
System.out.println("开始");
for (int i = 0; i < 10; i++) {
taskService.task(i);
}
System.out.println("结束");
Thread.sleep(10000);
}
}
注意事项:
如下方式会使@Async失效
一、异步方法使用static修饰
二、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
三、异步方法不能与被调用的异步方法在同一个类中
四、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
五、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解