看到坛子里一个淘宝的面试 题,自己随便写了一个

原帖地址在这里:http://www.iteye.com/topic/711162

引用
前几天在网上看到一个淘宝的面试题:有一个很大的整数list,需要求这个list中所有整数的和,写一个可以充分利用多核CPU的代码,来计算结果。


import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class BigListSum {

	/**
	 * @param args
	 */
	private static  List<Integer> list=new LinkedList<Integer>();
	private static int max=100000;
	public static List<Integer> setList(int max){
		for(int i=0;i<max;i++)
			list.add(i+1);
		//System.out.println(list.size());
		return list;
	}
	public static void main(String[] args)throws Exception {
		BigListSum bls=new BigListSum();
		BigListSum.setList(max);
		int threadCount=10;
		int len=list.size()/threadCount+1;
		AtomicCounter counter=bls.new AtomicCounter();
		for(int i=0;i<threadCount;i++){
			if(len*i<list.size())
				bls.new subThread("thread"+i,list,len*i,len,counter).start();
		}
	}
	class subThread extends Thread{
		private AtomicCounter counter;
		private List<Integer> childList;
		private int offset;
		private int len;
		
		protected subThread(String name,List<Integer> list,int offset,int len,AtomicCounter counter){
			super(name);
			this.counter=counter;
			this.offset=offset;
			if((offset+len)>list.size()){
				this.len=list.size()-offset;
			}else{
				this.len=len;
			}
			childList=list.subList(this.offset, this.offset+this.len);
			
		}
		
		public void run(){
			long sum=0;
			if(childList.size()>0){
				
				for(int i=0;i<childList.size();i++){
					sum+=childList.get((int)i);
				}
				counter.increment(sum);
			}
				System.out.println(Thread.currentThread().getName()+":["+
						this.childList.get(0)+"<-->"+this.childList.get(this.childList.size()-1)+
						"].count:"+counter.getValue());
		}
	}
	class AtomicCounter{
		private AtomicLong sum=new AtomicLong();
		
		public AtomicCounter(){
			
		}
		public AtomicCounter(long value){
			sum.set(value);
		}
		public long getValue(){
			return sum.get();
		}
		public long increment() {
			return sum.incrementAndGet();
		}
		public long increment(long i) {
			return sum.addAndGet(i);
		}
		public long decrement() {
			return sum.decrementAndGet();
		}
		public long decrement(long i) {
			return sum.addAndGet(-i);
		}
	}

}




output:

thread9:[90010<-->100000].count:949194955
thread0:[1<-->10001].count:999209956
thread8:[80009<-->90009].count:1849384965
thread1:[10002<-->20002].count:1999419967
thread7:[70008<-->80008].count:2749574975
thread2:[20003<-->30003].count:2999629978
thread6:[60007<-->70007].count:3649764985
thread3:[30004<-->40004].count:3999839989
thread5:[50006<-->60006].count:4549954995
thread4:[40005<-->50005].count:5000050000


利用的是原子操作,无同步

你可能感兴趣的:(java,面试)