list分批异步处理

    
        
        
        
        
        
        
        
        
        
        
            
        
    
        threadPool.execute(new Runnable() {
            public void run() {
                if (CollectionUtils.isNotEmpty(countyInfoVOList)) {
                    //分批处理
                    DataBatchUtils batchUtils = new DataBatchUtils(countyInfoVOList,200);
                    while (batchUtils.hasNext()){
                        List list = batchUtils.next();
                        业务处理逻辑
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
import com.google.common.collect.Iterables;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA
 */
public class DataBatchUtils implements Iterator> {

	private int batchSize;
	private List origin;
	private int index = 0;
	private List result;
	private int size = 0;

	public DataBatchUtils(List origin, int batchSize) {
		if (0 >= batchSize) {
			throw new RuntimeException();
		}

		this.batchSize = batchSize;
		this.origin = origin;
		this.size = null == origin ? 0 : origin.size();
		result = new ArrayList(batchSize);
	}

	@Override
	public boolean hasNext() {
		return index < size;
	}

	@Override
	public List next() {
		result.clear();
		for (int i = 0; i < batchSize && index < size; i++) {
			result.add(origin.get(index++));
		}
		return result;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	/**
	 * 批量插入ByGuava
	 *
	 * @param origin    需要批量操作的数据信任List
	 * @param batchSize 分批数
	 * @param 
	 * @return
	 */
	public static  List> batchInsert(List origin, int batchSize) {
		Iterable> subSets = Iterables.partition(origin, batchSize);
		Iterator> partitions = subSets.iterator();
		List> list = new LinkedList<>();
		while (partitions.hasNext()) {
			List sub = partitions.next();
			list.add(sub);
		}
		return list;
	}
}

 

 

 

 

 

 

 

你可能感兴趣的:(java)