1.@Async注解作用是什么?
@Async 注解是 Spring 框架提供的一个注解,用于标识一个方法是异步执行的。当一个方法被 @Async 注解修饰时,Spring 将会在方法调用时创建一个新的线程来异步执行该方法,而不是在当前线程中同步执行。
2.@Async注解怎么使用?
1.项目中添加如下依赖
<dependencies> <!-- springboot依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- springboot开发工具依赖,可实现代码热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- springboot测试依赖,可进行快捷代码功能测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.需要在自己项目中新增配置注解@EnableAsync,来开启spring的注解异步处理,使得可以通过@Async来实现异步执行 ,配置类如下:
package com.hz.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class SpringConfig {
}
3.异步服务
package com.hz.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsynService {
@Async
public void runAsyn(){
System.out.println(Thread.currentThread().getName()+"执行异步方法开始");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"执行异步方法结束");
}
}
4.测试调用异步方法
package com.hz;
import com.hz.service.AsynService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBootTestApplicationTests {
@Autowired
private AsynService asynService;
@Test
public void get(){
asynService.runAsyn();
System.out.println(Thread.currentThread().getName()+"执行方法结束");
}
}
5.执行结果
代码中先调用异步方法再打印主方法结束信息。上面实际执行结果中,主方法打印先结束,说明调用的异步子方法与主方法实现了异步执行。
3.本次测试使用的环境
windows11 + springboot 3.2.1 + openjdk 21