springboot多线程并发
时间: 2023-12-10 12:35:52 浏览: 36
以下是一个使用SpringBoot实现多线程下载文件的例子,其中使用了线程池和CountDownLatch来实现多线程并发:
```java
@RestController
public class DownloadController {
@Autowired
private DownloadService downloadService;
@GetMapping("/download")
public String download() throws InterruptedException {
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 创建CountDownLatch
CountDownLatch countDownLatch = new CountDownLatch(5);
// 开始下载
for (int i = 0; i < 5; i++) {
executorService.execute(() -> {
downloadService.download();
countDownLatch.countDown();
});
}
// 等待所有线程执行完毕
countDownLatch.await();
// 关闭线程池
executorService.shutdown();
return "下载完成!";
}
}
@Service
public class DownloadService {
public void download() {
// 下载文件的具体实现
}
}
```