主题:淘宝面试题:怎么充分利用多核CPU,计算很大的List中所有整数的和
主题:淘宝面试题:如何充分利用多核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(); } }