分批处理接口(抽象类)代码实例

package com.util;

import java.util.List;

/**
 * * @description 分批回调执行方法接口
 * */
public interface BatchHandlerInterface<T> {
    /**
     * 分批回调方法  需重写此方法
     * */
    public void handler(List<T> subList);
}
package com.util;

import java.util.List;

import org.apache.log4j.Logger;

/**
 * @description 分批调用方法接口  
 * */
public abstract class BatchHandlerList<T> implements BatchHandlerInterface<T> {
	
	private static final Logger LOGGER = Logger.getLogger(BatchHandlerList.class);
	//每次处理条数
	private Integer perNum;
	
	private List<T> aylist;

	public BatchHandlerList(Integer perNum, List<T> aylist) {
		super();
		this.perNum = perNum;
		this.aylist = aylist;
	}
	
	/**
	 * 分批调用方法  参考下面的线程池调用,  每个线程执行sublist长度的任务
	 * */
	public void handlerList(){
		try{
			if(aylist!=null && aylist.size() > 0){
				int size = aylist.size();
				int startIndex = 0;
				int endIndex = 1;
				int num = 1;
				if (size > perNum) {
					num = size / perNum;
				}
				for (int i = 1; i <= num; i++) {
					endIndex = (i) * perNum > size ? size : (i) * perNum;
					List<T> subList = aylist.subList(startIndex, endIndex);
					
					startIndex = perNum * i;
					if (subList!=null && subList.size() > 0) {
						handler(subList);
					}
					
					if (num == i && perNum * num < size) {
						//最后一批处理
						subList = aylist.subList(perNum * num, size);
						if (subList.size() > 0) {
							handler(subList);
						}
					}
			   }
			}
		}catch(Throwable e){
			LOGGER.error("batchHandlerList handler exception",e);
			//错误回调方法可以重写
			errorHandler();
		}
	}
	
	public void errorHandler(){};
}

以上是接口及抽象类,下面是调用及实现

 //组装数据
	   BatchHandlerList<String> handler = new BatchHandlerList<String>(20,waybillNos) {
			@Override
			public void handler(List<String> subList) {
				//这里的records用的是引用传递 后面要用
				SispRecieveInfoRequestRunnable sispRunable = new SispRecieveInfoRequestRunnable(subList, contextOrder, language, count, records);
				sispRecieveInfoExecutor.execute(sispRunable);
				runList.add(sispRunable);
			}
	   };
	   
	   //执行调用
	   handler.handlerList();

猜你喜欢

转载自blog.csdn.net/liao0801_123/article/details/81111604
今日推荐