public class DemoTest { public static void main(String[] args) throws Exception { sumCalculate(); } static class Calculate implements Callable<Integer> { int[] a; public Calculate() { } public Calculate(int[] a) { this.a = a; } public Integer call() throws Exception { // TODO Auto-generated method stub int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } } public static void sumCalculate() throws InterruptedException, ExecutionException { int core = Runtime.getRuntime().availablePRocessors(); int[] nums = {1,2,3,4,5,6,7,8,9,12,13,14}; double ceil = Math.ceil(nums.length / (core*1.0)); ExecutorService pool = Executors.newFixedThreadPool(core); List<FutureTask<Integer>> tasks = new ArrayList<FutureTask<Integer>>(); for (int i = 0; i < core; i++) { int[] a = new int[(int) ceil]; for (int j=0;j<ceil;j++){ if(i*(int)ceil+j >= nums.length) break; a[j]=nums[i*(int)ceil+j]; }; Calculate calculate = new Calculate(a); FutureTask<Integer> task = new FutureTask<Integer>(calculate); Future<?> submit = pool.submit(task); System.out.println(submit.getClass()); tasks.add(task); } int sum = 0; for (int i = 0; i < tasks.size(); i++) { FutureTask<Integer> futureTask = tasks.get(i); Integer integer = futureTask.get(); sum += integer; } System.out.println(sum); } }
新闻热点
疑难解答