ThreadPoolTask​​Executor产生不需要的线程

时间:2017-09-29 07:29:25

标签: java spring multithreading

我有两个配置为使用相同TaskExecutor的Async方法。

@Async("myExecutor") 
public void foo() {
    system.out.println("foo from: " + Thread.currentThread().getName());
}


@Async // this should use the primary defaultExecutor
// try to bombard the single thread pool with bunch of requests
public void generateFoo() {
    while(true) {
        system.out.println("generateBar from: " + Thread.currentThread().getName());
        this.foo();
    }
}

我希望myExecutor的下划线线程池的coreize和maxsize为1,并为该线程排队传入请求。即只有一个执行foo()的线程一次运行,所有其他对foo()的调用都等待轮到他们。在我的Spring配置类中,我有

@Configuration
@ComponentScan(basePackages = { "com.test" })
@EnableAsync
@EnableScheduling
public class FooBarConfig {

@Bean
@Primary
@Qualifier("defaultExecutor")
public TaskExecutor defaultExecutor() {
    return new ThreadPoolTaskExecutor();
}

@Bean
@Qualifier("myExecutor")
public TaskExecutor myExecutor() {

    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(1);
    executor.setMaxPoolSize(1);
    executor.setQueueCapacity(Integer.MAX_VALUE);
    return executor;
    }
}

但是,我发现foo()并不总是从同一个线程执行。如果我通过另一个线程的@Scheduled任务调用foo(),它会按预期在“myExecutor-1”上运行。但是如果通过generateFoo()调用foo(),它似乎是在运行的generateFoo()中运行,即:

foo from: defaultExecutor-1
foo from: myExecutor-1
foo from: defaultExecutor-1
foo from: defaultExecutor-1
foo from: defaultExecutor-1

如果我摆脱了generateFoo()的@Async,foo()仍会在运行generateFoo()的任何线程上运行。

我是否使用了错误的TaskExecutor来查找或正确配置它?

修改的 作为我原始帖子中的状态,没有像有人建议的那样使generateFoo()成为异步方法似乎没有做到这一点。

0 个答案:

没有答案