人最宝贵的是生命。它给予我们只有一次。人的一生应当这样度过:当他回首往事时不因虚度年华而悔恨,也不因碌碌无为而羞耻。这样在他临死的时侯就能够说:"我已把我整个的生命和全部精力都献给最壮丽的事业—为人类的解放而斗争"。新浪微博

一千万个数,高效求和

 1 private class SumTask extends RecursiveTask<Long> {
 2 
 3     private static final int THRESHOLD = 1250000;
 4 
 5     private long arr[];
 6     private int start;
 7     private int end;
 8 
 9     public SumTask(long[] arr, int start, int end) {
10         this.arr = arr;
11         this.start = start;
12         this.end = end;
13     }
14 
15     /**
16      * 小计
17      */
18     private long subtotal() {
19         long sum = 0;
20         for (int i = start; i < end; i++) {
21             sum += arr[i];
22         }
23 
24         return sum;
25     }
26 
27     @Override
28     protected Long compute() {
29 
30         if ((end - start) <= THRESHOLD) {
31             return subtotal();
32         }else {
33             int middle = (start + end) / 2;
34             SumTask left = new SumTask(arr, start, middle);
35             SumTask right = new SumTask(arr, middle, end);
36             left.fork();
37             right.fork();
38 
39             return left.join() + right.join();
40         }
41     }
42 }
43 
44 public static void main(String[] args) throws ExecutionException, InterruptedException{
45     int num = Runtime.getRuntime().availableProcessors();
46     long time = System.currentTimeMillis();
47     long[] arr = new long[10000000];
48     for (int i =0 ; i < 10000000; i++) {
49         arr[i] =i+1;
50     }
51 
52     ForkJoinPool pool = new ForkJoinPool();
53     ForkJoinTask<Long> result = pool.submit(new ForkJoinTest().new SumTask(arr, 0, arr.length));
54     System.out.println("最终计算结果: " + result.invoke()+"耗时:"+(System.currentTimeMillis() - time)+",毫秒");
55     pool.shutdown();
56 }

 

posted @ 2020-01-12 14:55  草根玉堂  阅读(1724)  评论(0编辑  收藏  举报