Mar*_* V. 24 spring multithreading asynchronous thread-synchronization
我的问题与此问题非常类似:@Async阻止线程继续,直到其他线程完成
基本上我需要在更多线程中运行〜数百次计算.我想只运行一些并行线程,例如5个线程,其中5个计算是并行的.
我使用spring框架和@Async选项是很自然的选择.我不需要全功能的JMS队列,这对我来说有点开销.
有任何想法吗 ?谢谢
Sig*_*gen 32
如果您使用的是Spring的Java配置,那么您的config类需要实现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;
}
}
Run Code Online (Sandbox Code Playgroud)
有关@EnableAsync更多详细信息,请参阅文档:http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html
jel*_*ies 19
你看过了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"/>
Run Code Online (Sandbox Code Playgroud)
这里完全参考(25.5.3).希望这可以帮助.
从 spring boot 2.1 开始,您可以使用自动配置并更改应用程序属性文件中的最大线程数
spring.task.execution.pool.max-size=4
Run Code Online (Sandbox Code Playgroud)
查看完整文档:https :
//docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-task-execution-scheduling