newFixedThreadPool与Callable结合用法
package com.sohu.test;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;/** * @author qiaowang * @date 2013-12-26 上午10:39:01 */public class TestThreadDemo { private ExecutorService exec; private int cpuNum; private List<Future<Long>> tasks = new ArrayList<Future<Long>>(); class SumCalculator implements Callable<Long> { private int[] numbers; private int start; private int end; public SumCalculator(final int[] numbers, int start, int end) { this.numbers = numbers; this.start = start; this.end = end; } public Long call() throws Exception { Long sum = 0l; for (int i = start; i < end; i++) { sum += numbers[i]; } return sum; } } public TestThreadDemo() { cpuNum = Runtime.getRuntime().availableProcessors(); exec = Executors.newFixedThreadPool(cpuNum); } public Long sum(final int[] numbers) { // 根据CPU核心个数拆分任务,创建FutureTask并提交到Executor System.out.println(cpuNum); for (int i = 0; i < cpuNum; i++) { int increment = numbers.length / cpuNum + 1; int start = increment * i; int end = increment * i + increment; if (end > numbers.length) end = numbers.length; SumCalculator subCalc = new SumCalculator(numbers, start, end); FutureTask<Long> task = new FutureTask<Long>(subCalc); tasks.add(task); if (!exec.isShutdown()) { exec.submit(task); } } return getResult(); } public Long getResult() { Long result = 0l; for(Future<Long> task : tasks){ try { Long subSum = task.get(); result +=subSum; } catch (Exception e) { e.printStackTrace(); } } return result; } public void close(){ exec.shutdown(); } public static void main(String args[]){ int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ,12}; TestThreadDemo calc = new TestThreadDemo(); Long sum = calc.sum(numbers); System.out.println(sum); calc.close(); }}