1. 程式人生 > >Spring執行緒池的使用demo

Spring執行緒池的使用demo

為了提高執行效率,專案使用了Spring的執行緒池,實行多執行緒並行執行。

Spring註冊執行緒池。

	<bean id ="taskExecutor"  class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >  
    <!-- 執行緒池維護執行緒的最少數量 -->  
		<property name ="corePoolSize" value ="5" />  
		    <!-- 執行緒池維護執行緒所允許的空閒時間 -->  
		<property name ="keepAliveSeconds" value ="10" />  
		    <!-- 執行緒池維護執行緒的最大數量 -->  
		<property name ="maxPoolSize" value ="20" />  
		    <!-- 執行緒池所使用的緩衝佇列 -->  
		<property name ="queueCapacity" value ="4" />  
	</bean>  

程式內呼叫執行緒池
ThreadPoolTaskExecutor excutor = (ThreadPoolTaskExecutor) SpringApplicationContextHolder.getSpringBean("taskExecutor");
		//按類別查詢產品任務列表
		List<Callable<List<Tproduct>>> tasks = new ArrayList<Callable<List<Tproduct>>>();
		//根據parent查詢孩子的任務列表
		List<Callable<List<Tcategory>>> categoryTask = new ArrayList<Callable<List<Tcategory>>>();
		//產品任務多執行緒列表
		List<ProductServiceTask> tasklist = new ArrayList<ProductServiceTask>();
		//列表多執行緒列表
		List<CategoryServiceTask> categorytasklist = new ArrayList<CategoryServiceTask>();
		//初始化類別任務
		for(Tcategory tcategory : list){
			List<Tcategory> blist = new ArrayList<Tcategory>();
			CategoryServiceTask task = new CategoryServiceTask(blist, tcategory);
			categoryTask.add(task);
			categorytasklist.add(task);
		}
		//阻塞任務執行
		excutor.getThreadPoolExecutor().invokeAll(categoryTask);
	//初始化產品任務
		for(CategoryServiceTask tcategory : categorytasklist){
			List<String> alist = new ArrayList();
			List<Tcategory> blist =tcategory.getBlist();
			for (Tcategory tcategory2 : blist) {
				alist.add(tcategory2.getId() + "");
			}
			List<Tproduct> productList = new ArrayList<Tproduct>();
			ProductServiceTask task = new ProductServiceTask(productList, alist);
			tasks.add(task);
			tasklist.add(task);
		}
		//阻塞產品查詢
		excutor.getThreadPoolExecutor().invokeAll(tasks);

callable介面的實現
public class ProductServiceTask implements Callable<List<Tproduct>> {

	private SysProductDAO proDAO;
	private 	List<Tproduct> productList;
	private List<String> resultList;
	public ProductServiceTask(List<Tproduct> productList, List<String> resultList) {
		this.productList = productList;
		this.resultList = resultList;
		proDAO = (SysProductDAO) SpringApplicationContextHolder.getSpringBean("sysProductDAO");
	}
	@Override
	public List<Tproduct> call() throws Exception {
		try {
			productList = proDAO.find4Product(resultList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return productList;
	}
	public List<Tproduct> getProductList() {
		return productList;
	}
	public void setProductList(List<Tproduct> productList) {
		this.productList = productList;
	}
	public List<String> getResultList() {
		return resultList;
	}
	public void setResultList(List<String> resultList) {
		this.resultList = resultList;
	}

}