public class ForkJoinTest { static class LongSumTask extends RecursiveAction { private static final long serialVersionUID = 3854484772112113675L; private final List<Integer> elements; private final LongAccumulator accumulator; LongSumTask(List<Integer> elements, LongAccumulator accumulator) { this.elements = elements; this.accumulator = accumulator; } @Override public void compute() { int size = elements.size(); int parts = size / 2; if(size > 1){ List<Integer> left = elements.subList(0,parts); List<Integer> right = elements.subList(parts,size); new LongSumTask(left,accumulator).fork().join(); System.out.println("size值:"+size+"=================parts值:"+parts); new LongSumTask(right,accumulator).fork().join(); }else{ if(elements.isEmpty()){ return; } Integer num = elements.get(0); System.out.println(Thread.currentThread().getName()+"num的总数:"+accumulator.get()+"----num的当前值为:"+num); accumulator.accumulate(num); } } } public static void main(String[] args) { ForkJoinPool forkJoinPool = new ForkJoinPool(); LongAccumulator accumulator = new LongAccumulator((left, right) -> { return left+right; },0); System.out.println("开始->"+accumulator.get()); List<Integer> params = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30); forkJoinPool.invoke(new LongSumTask(params,accumulator)); System.out.println("计算->"+accumulator.get()); } }
开始->0
ForkJoinPool-1-worker-1num的总数:0----num的当前值为:1
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:1----num的当前值为:2
size值:5=================parts值:2
ForkJoinPool-1-worker-1num的总数:3----num的当前值为:3
size值:3=================parts值:1
ForkJoinPool-1-worker-1num的总数:6----num的当前值为:4
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:10----num的当前值为:5
size值:10=================parts值:5
ForkJoinPool-1-worker-1num的总数:15----num的当前值为:6
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:21----num的当前值为:7
size值:5=================parts值:2
ForkJoinPool-1-worker-1num的总数:28----num的当前值为:8
size值:3=================parts值:1
ForkJoinPool-1-worker-1num的总数:36----num的当前值为:9
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:45----num的当前值为:10
size值:20=================parts值:10
ForkJoinPool-1-worker-1num的总数:55----num的当前值为:11
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:66----num的当前值为:12
size值:5=================parts值:2
ForkJoinPool-1-worker-1num的总数:78----num的当前值为:13
size值:3=================parts值:1
ForkJoinPool-1-worker-1num的总数:91----num的当前值为:14
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:105----num的当前值为:15
size值:10=================parts值:5
ForkJoinPool-1-worker-1num的总数:120----num的当前值为:16
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:136----num的当前值为:17
size值:5=================parts值:2
ForkJoinPool-1-worker-1num的总数:153----num的当前值为:18
size值:3=================parts值:1
ForkJoinPool-1-worker-1num的总数:171----num的当前值为:19
size值:2=================parts值:1
ForkJoinPool-1-worker-1num的总数:190----num的当前值为:20
计算->210