小言_互联网的博客

一千万个数,高效求和,forkjoin

311人阅读  评论(0)

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

 


转载:https://blog.csdn.net/byt420/article/details/105987512
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场