spring线程池的理解和使用

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));
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值