protected Long compute(){ Long length = end - start; if (length <= critical) { // 拆分完毕就相加 Long sum = 0L; for (Long i = start; i <= end; i++) { sum += i; } return sum; } // 没有拆分完毕就开始拆分 Long middle = (start + end) / 2; // 拆分并压入线程队列 ForkJoinWork left = new ForkJoinWork(start, middle); left.fork(); ForkJoinWork right = new ForkJoinWork(middle + 1, end); right.fork();
publicclassForkJoinWorkDemo{ privatestaticfinal Long start = 0L; privatestaticfinal Long end = 10_000_000_000L;
publicstaticvoidtest(){ long t0 = System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinWork task = new ForkJoinWork(start, end); Long invoke = forkJoinPool.invoke(task); long t1 = System.currentTimeMillis(); // invoke=-5340232216128654848 time: 76883 System.out.println("invoke=" + invoke + " time: " + (t1 - t0)); }
publicstaticvoidtest2(){ //普通实现 Long x = start; Long y = end; long l = System.currentTimeMillis(); for (Long i = 0L; i <= y; i++) { x += i; } long l1 = System.currentTimeMillis(); // invoke = -5340232216128654848 time: 81475 System.out.println("invoke = " + x + " time: " + (l1 - l)); }
publicstaticvoidtest3(){ //Java 8 并行流的实现 long l = System.currentTimeMillis(); long reduce = LongStream.rangeClosed(start, end).parallel().reduce(0, Long::sum); long l1 = System.currentTimeMillis(); // invoke = -5340232216128654848 time: 1727 System.out.println("invoke = " + reduce + " time: " + (l1 - l)); }
近期评论