1. package concurrent;
    2. import java.util.ArrayList;
    3. import java.util.concurrent.ExecutionException;
    4. import java.util.concurrent.ForkJoinPool;
    5. import java.util.concurrent.ForkJoinTask;
    6. import java.util.concurrent.RecursiveTask;
    7. public class C04_ForkJoin {
    8. /**
    9. * .《实战JAVA高并发程序设计》P117——3.2.9分而治之:Fork/Join
    10. * Fork/Join框架是将大任务分解成小任务,通过合成子任务的子结果而得到结果。
    11. * ForkJoinPool线程池
    12. * ForkJoinTask-----RecurisiveTask : 有返回值,通过 join()接收, 类似的接口有Callable
    13. * --RecursiveAction : 没有返回值
    14. * .下面以计算数列前n项和为例子
    15. */
    16. public static class CountTask extends RecursiveTask<Long> {
    17. private static final int MAX = 10000; //一个任务最多计算多少项的和
    18. private long start;
    19. private long end;
    20. public CountTask(long start, long end){ this.start = start; this.end = end; }
    21. @Override
    22. protected Long compute() {
    23. long sum = 0;
    24. boolean canCompute = (end - start) < MAX;
    25. if(canCompute){
    26. for(long i=start; i<=end; i++)
    27. sum+=i;
    28. }else{
    29. //分成100个小任务
    30. ArrayList<CountTask> countTasks = new ArrayList<>(100);
    31. long step = (end - start) / 100;
    32. for(long i = start ; i<end ; i+= step + 1){
    33. CountTask task = new CountTask(i, (i + step) < end ? (i + step) : end);
    34. countTasks.add(task);
    35. task.fork(); //执行
    36. }
    37. for(CountTask task : countTasks)
    38. sum += task.join();
    39. }
    40. return sum;
    41. }
    42. }
    43. public static void main(String[] args){
    44. ForkJoinPool forkJoinPool = new ForkJoinPool();
    45. CountTask task = new CountTask(0L, 500000L);
    46. ForkJoinTask<Long> result = forkJoinPool.submit(task);
    47. try{
    48. long res = result.get(); //获得结果
    49. System.out.println("result = " + res);
    50. } catch (InterruptedException e) {
    51. e.printStackTrace();
    52. } catch (ExecutionException e) {
    53. e.printStackTrace();
    54. }
    55. forkJoinPool.shutdown();
    56. }
    57. }

    console

    1. result = 125000250000