读书人

看到罐子里一个淘宝的面试 题自己随

发布时间: 2012-12-26 14:39:28 作者: rapoo

看到坛子里一个淘宝的面试 题,自己随便写了一个
原帖地址在这里:http://www.iteye.com/topic/711162

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


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

读书人网 >编程

热点推荐