先简单介绍下同步和异步的概念:
同步:按顺序执行
异步:同时执行
在Java程序中,大部分代码基本都是同步执行的,如果程序使用异步执行的话,可以大大提高执行的效率。一般情况下,我们会使用多线程、中间件、还有@Async来实现程序的异步执行。
@Async
spring 3.x之后,就内置了@Async,下面直接来看如何使用@Async
- 创建异步配置类
@EnableAsync 开启异步支持
配置线程池相关属性
可以自定义多个线程池,通过@Async(“线程池名称”)指定线程池
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author CTW
*/
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 设置最大线程数
executor.setMaxPoolSize(10);
// 设置队列容量
executor.setQueueCapacity(20);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("Test-Async");
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
- @Async注解的使用
两种情况:1.方法无返回,2.方法有返回
@Async 可以写在接口上,也可以写在实现类上
- 无返回
@Async
public void testAsync1() {
long startTime = System.currentTimeMillis();
try {
//模拟耗时
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis(