线程springboot
时间: 2025-01-06 14:36:22 浏览: 7
### Spring Boot 中线程使用教程
#### 开启异步支持
为了在Spring Boot应用程序中启用多线程处理,需添加`@EnableAsync`注解到主类上。这会激活基于代理的异步方法执行功能[^2]。
```java
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
#### 配置线程池
可以通过定义一个`TaskExecutor` Bean来自定义线程池配置。这样可以依据应用的具体需求调整诸如核心线程数、最大线程数等参数[^1]。
```java
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
publicAdviceMode getOrder() {
return AdviceMode.PROXY;
}
@Override
public boolean isProxyTargetClass() {
return true;
}
}
```
#### 定义异步服务
创建带有`@Async`注解的方法,在调用这些方法时它们将在单独的工作线程中运行而不是阻塞主线程[^3]。
```java
@Service
public class AsyncTaskService {
@Async
public void executeAsyncTask(int i) throws InterruptedException {
System.out.println(
"Start process [" + i + "] at Thread["
+ Thread.currentThread().getName() + "]");
// Simulate task processing time.
Thread.sleep(1000);
System.out.println(
"End process [" + i + "] at Thread["
+ Thread.currentThread().getName() + "]");
}
}
```
#### 编写测试案例验证效果
编写单元测试来检验异步操作是否按预期工作。这里展示了一个简单的例子,其中循环调用了之前定义的服务方法多次。
```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private AsyncTaskService asyncTaskService;
@Test
public void testMultiThreadExecution() throws Exception {
for (int i = 0; i < 20; ++i) {
asyncTaskService.executeAsyncTask(i);
}
// Wait all tasks to complete before ending the program.
TimeUnit.SECONDS.sleep(25);
}
}
```
阅读全文