【发布时间】:2019-11-07 00:28:26
【问题描述】:
我在应用程序上下文中创建了一个 bean 线程池执行器。我想使用该线程池执行器并在另一个类中运行一些代码,该类注释为@Service。
我的应用类
public class TestApplication extends WebMvcConfigurerAdapter {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/resources/", "classpath:/static/"};
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
public Executor testAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(10);
executor.setThreadNamePrefix("TestExecutor-");
executor.initialize();
return executor;
}
}
下面的类是我需要执行该线程的地方
@Service
public class TastService{
public void runMyCode(){
//Here I need to start that thread and then call executor.submit()
}
}
【问题讨论】:
-
不要...只需将
@Async放在方法上即可。为什么你需要自己提交薄?如果您真的需要它,只需自动连接TaskExecutor并使用它。 -
当我使用
@Autowire注释应用程序失败并出现无法绑定的错误。我不能使用@Async,因为我想要当前线程上的一些上下文数据到新的起始线程。这就是为什么我试图通过 Spring Boot 获取线程 -
将
@Bean方法的返回类型更改为ThreadPoolTaskExecutor,然后注入TaskExecutor(不是完整类型,只是接口!)。
标签: java spring threadpool