33

我的问题与这个问题非常相似:@Async prevent a thread to continue until other thread has done

基本上我需要在更多线程中运行〜数百次计算。我只想运行一定数量的并行线程,例如并行运行 5 个线程和 5 个计算。

我正在使用 spring 框架,@Async 选项是自然的选择。我不需要功能齐全的 JMS 队列,这对我来说有点开销。

有任何想法吗 ?谢谢

4

3 回答 3

40

如果你使用 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

于 2014-05-07T08:12:37.110 回答
20

你检查了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)。希望这可以帮助。

于 2012-11-03T06:54:51.867 回答
10

从 Spring Boot 2.1开始,您可以使用自动配置并更改应用程序属性文件中的最大线程数

spring.task.execution.pool.max-size=4

查看完整文档:
https ://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-task-execution-scheduling

于 2019-10-03T08:44:05.883 回答