springboot 使用多线程
时间: 2023-09-10 11:10:56 浏览: 102
解决SpringBoot2多线程无法注入的问题
在Spring Boot中使用多线程可以有多种方式。
1. 继承Thread类
```java
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行代码
}
}
```
然后在Spring Boot中调用该线程:
```java
MyThread thread = new MyThread();
thread.start();
```
2. 实现Runnable接口
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行代码
}
}
```
然后在Spring Boot中调用该线程:
```java
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```
3. 使用线程池
```java
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
}
```
然后在Spring Boot中调用该线程池:
```java
@Autowired
private Executor executor;
public void runTask() {
executor.execute(new Runnable() {
@Override
public void run() {
// 线程执行代码
}
});
}
```
以上是几种在Spring Boot中使用多线程的方式,具体选择哪种方式取决于实际业务需求和个人偏好。
阅读全文