使用Spring 线程池
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 线程池维护线程的最少数量 --> <property name="corePoolSize" value="3" /> <!-- 线程池维护线程所允许的空闲时间 --> <property name="keepAliveSeconds" value="200" /> <!-- 线程池维护线程的最大数量 --> <property name="maxPoolSize" value="5" /> <!-- 线程池所使用的缓冲队列 --> <property name="queueCapacity" value="25" /> </bean> </beans>
以上为线程池的一些配置。
写了一个service,初始化线程池,并且,作为一个调用线程的接口
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
@Component
public class ThreadPoolTaskService {
private ApplicationContext ctx;
private ThreadPoolTaskExecutor taskExecutor;
public ThreadPoolTaskService () {
ctx = new ClassPathXmlApplicationContext("threadpool.xml");
taskExecutor = (ThreadPoolTaskExecutor) ctx.getBean("taskExecutor");
}
public void execute(Runnable runnable) {
if (null != taskExecutor) {
taskExecutor.execute(runnable);
}
}
}
再写一个runnable
public class TesetThread implements Runnable { private List<String> list; private TestAService testAService; public TestThread() { } public TestThread(List<String> list, TestAService testAService) { this.list = jobList; this.testAService = testAService; } @Override public void run() { testAService.deal(list); } }
使用的时候
@Autowired
private ThreadPoolTaskService threadPoolTaskService;
threadPoolTaskService.execute(new TestThread(list, testAService));

浙公网安备 33010602011771号