本文主要是介绍主题:淘宝面试题:如何充分利用多核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 > 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 > 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 > 0;this.countThread = countThread;}private void checkGameOver() {if (isGameOver()) notifyAll();}public synchronized boolean isGameOver() {return countFinish >= countThread;}public synchronized void addSum(long v) {sum = sum == null ? new BigDecimal(v) : sum.add(BigDecimal.valueOf(v));}public synchronized void finishA() {countFinish++;checkGameOver();}
}
这篇关于主题:淘宝面试题:如何充分利用多核CPU,计算很大的List中所有整数的和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!