ForkJoinDemo

package test.java.com.example;

import java.util.List;
import java.util.Random;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ForkJoinDemo {

    public static void main(String[] args) {

        List<Integer> integers = Stream.generate(() -> {
            return new Random().nextInt(999999);
        }).limit(1000).collect(Collectors.toList());

        Integer reslut = new Integer(0);
        Counter counter = new Counter(0, integers.size(), integers, reslut);

        reslut = counter.compute();

    }
}


class Counter extends RecursiveTask<Integer> {
    //二分阈值
    public static final int THRESHOLD = 10;

    private int from;

    private int to;

    private List<Integer> targetList;

    private Integer result;


    public Counter(int from, int to, List<Integer> targetList, Integer result) {
        this.from = from;
        this.to = to;
        this.targetList = targetList;
        this.result = result;
    }

    @Override
    protected Integer compute() {

        if (to - from < THRESHOLD) {
            //前闭后开,传入元素的时候直接传size就行,不会下标越界
            for (int i = from; i < to; i++) {
                result += targetList.get(i);
            }
            return result;
        } else {
            int mid = (from + to) >> 1;
            Counter first = new Counter(from, mid, targetList, result);
            Counter second = new Counter(mid, to, targetList, result);
            invokeAll(first, second);
            return first.join() + second.join();
        }
    }

}

你可能感兴趣的:(JUC)