Spring线程池ThreadPoolTaskExecutor配置过程以及调用

时间:2022-05-20 18:25:34

一、这种方法调用起来比较简单,但是不推荐使用:

1、初始化线程池

  1. ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();  
  2. poolTaskExecutor.setQueueCapacity(10000);  
  3. poolTaskExecutor.setCorePoolSize(5);  
  4. poolTaskExecutor.setMaxPoolSize(10);  
  5. poolTaskExecutor.setKeepAliveSeconds(5000);  
  6. poolTaskExecutor.initialize(); 

2、在线程池中执行某个线程

  1. poolTaskExecutor.execute(new Thread(Objct...){...});  


二、这种方法是我成功使用,且用的是xml配置线程池(推荐使用)

1、ThreadPoolBean.xml为线程池初始化配置文件,放在src\main\resources文件夹下,这样方便ClassPathXmlApplicationContext用classpath查找。

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd


http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">

<context:component-scan base-package="com.suning" />
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
           <!-- 线程池维护线程的最少数量 -->
           <property name="corePoolSize" value="5" />
           <!-- 允许的空闲时间 -->
           <property name="keepAliveSeconds" value="200" />
           <!-- 线程池维护线程的最大数量 -->
           <property name="maxPoolSize" value="10" />
           <!-- 缓存队列 -->
           <property name="queueCapacity" value="20" />
           <!-- 对拒绝task的处理策略 -->
           <property name="rejectedExecutionHandler">
              <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
           </property>
        </bean>
</beans>


2、执行线程类:

package com.suning.commonlib;


import com.suning.snRedis.RedisAccess;


public class MultiThread implements Runnable{
static private RedisAccess redisAccess = new RedisAccess();
    String newprocessedQuery;
    String newresult;
public MultiThread() {
}
    
public MultiThread(String newprocessedQuery, String newresult) {
   this.newprocessedQuery = newprocessedQuery;
   this.newresult = newresult;
}
    
@Override
public void run() {
redisAccess.hset(newprocessedQuery, "suning_rqss", newresult);
}
}

3、调用线程:

 ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:ThreadPoolBean.xml");

ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) appContext.getBean("taskExecutor");

String processedQuery = “”;

String result = “”;

taskExecutor.execute(new MultiThread(processedQuery, result));