1、spring线程池
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 线程池维护线程的最少数量,默认为1 -->
<property name="corePoolSize" value="5" />
<!-- 线程池维护线程的最大数量,默认为Integer.MAX_VALUE -->
<property name="maxPoolSize" value="10" />
<!-- 允许的空闲时间,单位/秒,默认60秒 -->
<property name="keepAliveSeconds" value="200" />
<!-- 缓存队列个数,默认为Integer.MAX_VALUE -->
<property name="queueCapacity" value="20" />
<!-- 对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.-->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
2、测试线程池
- 需要的jar包
- 测试代码:
package com.yw.thread.spring;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class MyThreadTaskTest {
//@Autowired
//private ThreadPoolTaskExecutor taskExecutor;
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
new MyThreadTaskTest().testTaskExecutor(taskExecutor);
new MyThreadTaskTest().testTaskExecutor(taskExecutor);
}
public void testTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
List<String> list = new ArrayList<String>();
list.add("章程");
list.add("流苏");
list.add("漾须");
Map<String, String> map = new HashMap<String, String>();
for (int i=0; i<10; i++) {
taskExecutor.execute(new testFor(list, map));
}
//不需要shutdown,否则这个线程池用过一次就不能再用了
//taskExecutor.shutdown();
//如果想要所有子线程执行完再执行主线程,那么就需要直接用到taskExecutor.getActiveCount()来判断
while(true){
if(taskExecutor.getActiveCount() == 0){
break;
}
Thread.sleep(200);
}
System.out.println("执行完毕===========================");
System.out.println(map.toString());
}
}
class testFor implements Runnable{
private List<String> list;
private Map<String, String> map;
public testFor(List<String> list, Map<String, String> map) {
this.list = list;
this.map = map;
}
@Override
public void run() {
for (int i = 0; i < list.size(); i++) {
System.out.println(Thread.currentThread().getName()+"="+list.get(i));
map.put(Thread.currentThread().getName()+ "----" + i, list.get(i));
}
}
}