我的问题与这个问题非常相似:@Async prevent a thread to continue until other thread have finished
基本上,我需要在多个线程中运行数百个计算。我希望只运行一些并行线程,例如5个线程,每个线程中有5个计算。
我正在使用Spring框架和@Async选项是自然的选择。我不需要完整功能的JMS队列,那对我来说有点超额。
有什么想法吗? 谢谢
我的问题与这个问题非常相似:@Async prevent a thread to continue until other thread have finished
基本上,我需要在多个线程中运行数百个计算。我希望只运行一些并行线程,例如5个线程,每个线程中有5个计算。
我正在使用Spring框架和@Async选项是自然的选择。我不需要完整功能的JMS队列,那对我来说有点超额。
有什么想法吗? 谢谢
如果你正在使用Spring的Java配置,则你的配置类需要实现AsyncConfigurer
:
@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer {
[...]
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(50);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
}
请参阅@EnableAsync
文档以获取更多详细信息:http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html
你是否查看了任务执行器
?您可以定义线程池,其中包含最大数量的线程来执行您的任务。
如果您想要与@Async
一起使用它,请在您的Spring配置中使用此选项:
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>
完整的参考资料在此处(25.5.3)。希望这可以帮到您。
自Spring Boot 2.1起,你可以在应用程序属性文件中使用自动配置并更改最大线程数。
spring.task.execution.pool.max-size=4
@Async
注释多个方法,它们将共享由@EnableAsync
配置定义的线程池/执行器。 - Siggen