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

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

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


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


利用的是原子操作,无同步
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值