1.Springmvc线程池配置:
在spring上下文文件ApplicationContext.xml中添加
<!-- 线程池配置 -->
<bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="5" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="30" />
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="500" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="200" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
2.线程池的使用:
在需要调用的业务service调用线程
1)先定义引用
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
2)我这边操作的业务是给图片压缩 (这里的picList是图片集合,这里当参数传给线程类)
private void uploadPic(){
//图片集合
List<String> picList=new ArrayList<String>();
//上传图片业务逻辑
...
//处理压缩图片任务
intLogger.info("DiseaseCourseInterface|uploadPic 当前线程数:"+taskExecutor.getActiveCount());
Schedule schedule=new Schedule(picList);
taskExecutor.execute(schedule);
}
3)创建一个线程类Schedule,处理压缩图片任务
public class Schedule implements Runnable{
//日志
protected Logger logger = Logger.getLogger(this.getClass());
//参数处理
private List<String> picList;
public Schedule(List<String> picList) {
this.picList = picList;
}
@Override
public void run() {
logger.info("[Schedule][execute]method begin ...");
try {
if(null!=picList&&picList.size()>0){
for (String pic : picList) {
//可直接获得图片list,这里处理压缩图片业务
...
}
}
} catch (Exception e) {
logger.error("[Schedule][execute]method error...");
}
logger.info("[Schedule][execute]method end ...");
}
}