一、初始化
1,直接调用
- ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
- //线程池所使用的缓冲队列
- poolTaskExecutor.setQueueCapacity(200);
- //线程池维护线程的最少数量
- poolTaskExecutor.setCorePoolSize(5);
- //线程池维护线程的最大数量
- poolTaskExecutor.setMaxPoolSize(1000);
- //线程池维护线程所允许的空闲时间
- poolTaskExecutor.setKeepAliveSeconds(30000);
- poolTaskExecutor.initialize();
2、配置文件
- <!-- 配置线程池 -->
- <bean id ="taskExecutor" class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
- <!-- 线程池维护线程的最少数量 -->
- <span style="white-space:pre"> </span><property name ="corePoolSize" value ="5" />
- <!-- 线程池维护线程所允许的空闲时间 -->
- <span style="white-space:pre"> </span><property name ="keepAliveSeconds" value ="30000" />
- <!-- 线程池维护线程的最大数量 -->
- <span style="white-space:pre"> </span><property name ="maxPoolSize" value ="1000" />
- <!-- 线程池所使用的缓冲队列 -->
- <span style="white-space:pre"> </span><property name ="queueCapacity" value ="200" />
- </bean>
程序里面获取:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ThreadPoolTaskExecutor poolTaskExecutor = (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
二、利用线程池启动线程
Thread udpThread = new Thread(udp);
poolTaskExecutor.execute(udpThread);
获取当前线程池活动的线程数:
int count = poolTaskExecutor.getActiveCount();
logger.debug("[x] - now threadpool active threads totalNum : " +count);