我对 ThreadPoolTaskExecutor 有以下配置
<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
<property name="maxPoolSize" value="25" />
<property name="queueCapacity" value="30" />
</bean>
我的公共(public)类 AdminService 中有 2 个方法。
- 无效triggerJob();
- boolean executeSql(String sql);
如何将ThreadPoolTaskExecutor插入triggerJob方法中,以便在第一个方法内调用executeSql时创建新线程。
在triggerjob内部,我有一个循环,根据条件调用executeSql。
我是否需要创建一个实现 runnable 的私有(private)类,以便 ThreadPoolTaskExecutor 可以执行此类,或者是否可以创建没有 runnable 的线程?
我的想法是这样的
@Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor;
void triggerJob(){
for( Object k:Objects){
if(k.equals(something){
//here new thread to be created somehow
threadPoolTaskExecutor.execute(executeSql(k.getSql())
}
}
}
最佳答案
如果你必须这样做,你可以使用org.springframework.core.task.SimpleAsyncTaskExecutor
:
<bean id="simpleTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
<property name="concurrencyLimit" value="25" />
</bean>
但是创建 Java 线程的成本很高。通常建议重用线程,甚至 SimpleAsyncTaskExecutor docs说:
NOTE: This implementation does not reuse threads! Consider a thread-pooling TaskExecutor implementation instead, in particular for executing a large number of short-lived tasks.
关于java - spring ThreadPoolTaskExecutor 在每个方法调用上创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630844/