首页 > 编程 > Java > 正文

java 并发计算数组和的示例

2019-11-06 06:37:09
字体:
来源:转载
供稿:网友
//java 并发计算数组和的示例
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);							}		}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表