public class ForkJoinPoolTest { public static void main(String[] args) throws ExecutionException, InterruptedException { int[] arr = new int[]{1,2,3,4,5,6}; LongSum longSum = new LongSum(0,arr.length,arr); ExecutorService executorService = Executors.newCachedThreadPool(); // executorService.submit(longSum); ForkJoinPool forkJoinPool = new ForkJoinPool(12); ForkJoinTask<Long> submit = forkJoinPool.submit(longSum); Long aLong = submit.get(); System.out.println(aLong); forkJoinPool.shutdown(); } static class LongSum extends RecursiveTask<Long> { static final int SEQUENTIAL_THREAD = 1000; int low; int high; int[] arr; LongSum(int low,int high,int[] arr){ this.low = low; this.high = high; this.arr = arr; } @Override protected Long compute() { if(high-low<=SEQUENTIAL_THREAD){ long sum = 0; for(int i = low; i<high;i++){ sum+=arr[i]; } return sum; }else { int mid = low+(high-low)/2; LongSum left = new LongSum(low, mid, arr); LongSum right = new LongSum(mid, high, arr); left.fork(); right.fork(); Long r = right.join(); Long l = left.join(); return r+l; } } } }
ForkJoinDemo
最新推荐文章于 2022-06-10 17:29:25 发布