springboot多线程案例
时间: 2023-09-11 13:05:04 浏览: 144
好的,这里提供一个简单的 Spring Boot 多线程案例,可以帮助你理解如何在 Spring Boot 中使用多线程。
首先,你需要在 pom.xml 文件中引入 Spring Boot 的多线程依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-task</artifactId>
</dependency>
```
接下来,你需要创建一个异步方法,在该方法上添加 `@Async` 注解来标识该方法是异步执行的,具体实现如下:
```
@Service
public class MyService {
@Async
public CompletableFuture<String> asyncMethod() throws InterruptedException {
Thread.sleep(5000);
return CompletableFuture.completedFuture("Hello World!");
}
}
```
在上面的代码中,我们使用了 `@Async` 注解来标识该方法是异步执行的,并且在异步方法中添加了一个 5 秒的延迟,然后返回一个 `CompletableFuture` 对象。
最后,你可以在控制器中调用异步方法,如下所示:
```
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public CompletableFuture<String> async() throws InterruptedException {
return myService.asyncMethod();
}
}
```
在上面的代码中,我们注入了 `MyService` 对象,并在控制器中创建了一个 `/async` 路径,当访问该路径时,会执行异步方法并返回一个 `CompletableFuture` 对象。
这就是一个简单的 Spring Boot 多线程案例,希望对你有所帮助。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)