快速巨量LIST数据处理

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class LargSumWithCallable {

	static int threadCounts = 50;// 使用的线程数
	static long sum = 0;

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		System.out.println("===========" +  System.currentTimeMillis()  );
		List<Integer> list = new ArrayList<Integer>();
		for (int j = 0; j <= 10003; j++) {
			list.add(j);
		}
		int len = list.size() / threadCounts;// 平均分割List
		// List中的数量没有线程数多(很少存在)
		if (len == 0) {
			threadCounts = list.size();// 采用一个线程处理List中的一个元素
			len = list.size() / threadCounts;// 重新平均分割List
		}
		List<Callable<Long>> callList = new ArrayList<Callable<Long>>();
		for (int i = 0; i < threadCounts; i++) {
			final List<Integer> subList;
			if (i == threadCounts - 1) {
				subList = list.subList(i * len, list.size());
			} else {
				subList = list.subList(i * len, len * (i + 1) > list.size() ? list.size() : len * (i + 1));
			}
			// 采用匿名内部类实现
			callList.add(new Callable<Long>() {
				public Long call() throws Exception {
					long subSum = 0L;
					for (Integer i : subList) {
						subSum += i;
						try {
	                        Thread.sleep(10);//相当于业务逻辑处理
	                    } catch (InterruptedException e) {
	                        e.printStackTrace();
	                    }
					}
					//System.out.println("分配给线程:" + Thread.currentThread().getName() + "那一部分List的整数和为:\tSubSum:" + subSum);
					return subSum;
				}
			});
		}
		
		ExecutorService exec = Executors.newFixedThreadPool(threadCounts);
		List<Future<Long>> futureList = exec.invokeAll(callList);
		for (Future<Long> future : futureList) {
			sum += future.get();
		}
		exec.shutdown();
		System.out.println(sum);
		System.out.println("===========" +  System.currentTimeMillis()  );
		sum=0;
		for (int j = 0; j < list.size(); j++) {
			sum += list.get(j);
			try {
                Thread.sleep(10);//相当于业务逻辑处理
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
		}
		System.out.println(sum);
		System.out.println("===========" +  System.currentTimeMillis()  );
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值