我的问题与这个问题非常相似:@Async prevent a thread to continue until other thread has done
基本上我需要在更多线程中运行〜数百次计算。我只想运行一定数量的并行线程,例如并行运行 5 个线程和 5 个计算。
我正在使用 spring 框架,@Async 选项是自然的选择。我不需要功能齐全的 JMS 队列,这对我来说有点开销。
有任何想法吗 ?谢谢
我的问题与这个问题非常相似:@Async prevent a thread to continue until other thread has done
基本上我需要在更多线程中运行〜数百次计算。我只想运行一定数量的并行线程,例如并行运行 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
你检查了Task Executor
吗?您可以定义一个线程池,使用最大数量的线程来执行您的任务。
如果您想将它与 一起@Async
使用,请在您的 spring-config 中使用它:
<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