ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
实现异步任务的步骤如下: **1. 创建一个SpringBoot项目** ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> ``` **2. 在启动类上标注注解`@EnableAsync`开启异步支持** ```java @EnableAsync @SpringBootApplication public class Springboot04TaskApplication { public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } } ``` **3. 在需要异步的类或方法上标注注解`@Async`说明当前的类或方法是异步任务** ```java @Slf4j @Service public class AsyncService { @Async public void async01() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("AsyncService -> async01"); } } ``` **4. 其它类的同步方法调用异步方法** ```java @Slf4j @RestController public class AsyncController { @Autowired AsyncService asyncService; @GetMapping("/sync01") public void sync01() { log.info("AsyncController -> sync01 -> 001"); //同步方法中调用异步方法 asyncService.async01(); log.info("AsyncController -> sync01 -> 002"); } } ``` 日志打印顺序如下,根据打印日志的顺序,说明异步任务调用成功了。 ``` 2022-09-07 10:52:31 : AsyncController -> sync01 -> 001 2022-09-07 10:52:31 : AsyncController -> sync01 -> 002 -- 等待5s后打印下面日志 2022-09-07 10:52:36 : AsyncService -> async01 ```