In one sentence: break down big tasks into smaller ones

demo

1 to 10 _0000_0000


package com.company;

import java.util.concurrent.RecursiveTask;

/ * * *@author shoukailiang
 * @version 1.0
 * @date 2021/8/8 17:21
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    / / the critical value
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute(a) {
        if ((end-start)<temp){
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else{
            / / forkjoin recursion
            long middle = (start + end) / 2; / / intermediate value
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork(); // Split the task and push it into the thread queue
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task2.fork(); // Split the task and push it into the thread queue
            returntask1.join() + task2.join(); }}}Copy the code

The three methods are compared and tested

class TestFork{
    // Loop calculation
    public static void test1(a){
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 10 _0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"Time:"+(end-start));
    }
    //ForkJoin
    public static void test2(a) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo forkJoinDemo = new ForkJoinDemo(0L.10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinDemo);
        Long sum  = submit.get();// Get the result
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"Time:"+(end-start));
    }
    / / parallel flows
    public static void test3(a){
        long start = System.currentTimeMillis();
        // Stream parallel Stream () (]
        long sum = LongStream
                .rangeClosed(0L.10_0000_0000L) // Calculate range (,]
                .parallel() // Parallel computing
                .reduce(0, Long::sum); // Output the result

        long end = System.currentTimeMillis();
        System.out.println("sum="+"Time:"+(end-start));
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException { test1(); test2(); test3(); }}Copy the code

The results of

Sum =500000000500000000 time: 6776 sum=500000000500000000 Time: 5497 sum=500000000500000000 Time: 79Copy the code