Spring Boot 多线程实现方式详解:Thread & @Async
Spring Boot 中使用多线程可以通过以下两种方式实现:
- 继承 Thread 类或实现 Runnable 接口,在 run 方法中定义线程执行的逻辑。然后通过 Thread 类的 start 方法启动线程。
@Component
public class MyThread implements Runnable {
@Override
public void run() {
// 线程执行的逻辑
}
}
@Service
public class MyService {
@Autowired
private MyThread myThread;
public void startThread() {
Thread thread = new Thread(myThread);
thread.start();
}
}
- 使用 Java 的线程池来管理线程,可以通过 Spring Boot 提供的 @Async 注解来实现异步执行。在方法上添加 @Async 注解后,Spring Boot 会自动创建一个线程池来执行该方法。
@Service
public class MyService {
@Async
public void asyncMethod() {
// 异步执行的逻辑
}
}
需要在启动类上添加 @EnableAsync 注解启用异步执行功能。
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nPGS 著作权归作者所有。请勿转载和采集!