`
skzr.org
  • 浏览: 355303 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

主题:淘宝面试题:如何充分利用多核CPU,计算很大的List中所有整数的和

阅读更多
如题:论坛帖子地址

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class MyWorkThread extends Thread {
	private List<integer> list;
	private int start, end;
	private long value;
	private Result result;

	
	public MyWorkThread(List<integer> list, Integer start, Integer end, Result result) {
		this.list = list;
		this.start = start;
		this.end = end;
		this.result = result;
	}


	private void add(int v) {
		if (Long.MAX_VALUE - v &gt; value) {
			value += v;
		} else {
			result.addSum(value);
			value = v;
		}
	}

	public void run() {
		try {
			for(int i = start; i  list = new ArrayList<integer>();
		for (int i = 0; i  threads = new ArrayList<thread>();
		for (;;) {
			end = start + len;
			if (end &gt; list.size()) end = list.size();
			threads.add(new MyWorkThread(list, start, end, result));
			start = end;
			if (start == list.size()) break;
		}
		result.setCountThread(threads.size());
		
		for (Thread thread : threads) {
			thread.start();
		}
		
		synchronized (result) {
			while(!result.isGameOver()) result.wait();
		}
		System.out.println("和为:" + result.getSum());
	}
}

class Result {
	private BigDecimal sum;
	private int countFinish, countThread;
	
	
	public BigDecimal getSum() {
		return sum;
	}
	
	public void setCountThread(int countThread) {
		assert countThread &gt; 0;
		this.countThread = countThread;
	}
	
	
	private void checkGameOver() {
		if (isGameOver()) notifyAll();
	}
	
	public synchronized boolean isGameOver() {
		return countFinish &gt;= countThread;
	}
	
	public synchronized void addSum(long v) {
		sum = sum == null ? new BigDecimal(v) : sum.add(BigDecimal.valueOf(v));
	}
	
	public synchronized void finishA() {
		countFinish++;
		checkGameOver();
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics