• 一千万个数,高效求和


     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 }
  • 相关阅读:
    android WebView 加载html5
    android 摄像头的使用
    android 传感器类 sensor
    关于java的一些东西
    android 网络连接管理机制
    利用Layout实现Button的不规则布局
    Android 推送通知指南(转载)
    android开发小问题随记(附1)
    ubuntu下搭建android开发环境(转载)
    北斗小辣椒双核升级攻略之一
  • 原文地址:https://www.cnblogs.com/ytxiao/p/12182686.html
Copyright © 2020-2023  润新知