1. @Slf4j(topic = "e")
    2. public class ForkJoinTest2 extends RecursiveTask<Long> {
    3. private Long start; // 1
    4. private Long end; // 1990900000
    5. // 临界值
    6. private Long temp = 10000L;
    7. public ForkJoinTest2(Long start, Long end) {
    8. this.start = start;
    9. this.end = end;
    10. }
    11. // 计算方法
    12. @Override
    13. protected Long compute() {
    14. ReentrantLock lock = new ReentrantLock();
    15. //tiao
    16. Condition condition = lock.newCondition();
    17. lock.newCondition();
    18. if ((end-start)<temp){
    19. Long sum = 0L;
    20. for (Long i = start; i <= end; i++) {
    21. sum += i;
    22. }
    23. return sum;
    24. }else { // forkjoin 递归
    25. long middle = (start + end) / 2; // 中间值
    26. ForkJoinTest2 task1 = new ForkJoinTest2(start, middle);
    27. task1.fork(); // 拆分任务,把任务压入线程队列
    28. ForkJoinTest2 task2 = new ForkJoinTest2(middle+1, end);
    29. task2.fork(); // 拆分任务,把任务压入线程队列
    30. return task1.join() + task2.join();
    31. }
    32. }
    33. public static void main(String[] args) throws ExecutionException, InterruptedException {
    34. //6596
    35. // test1();
    36. //4872
    37. // test2();
    38. //160
    39. test3();
    40. }
    41. /**
    42. * 单线程的直接10亿累加
    43. */
    44. public static void test1(){
    45. Long sum = 0L;
    46. long start = System.currentTimeMillis();
    47. for (Long i = 1L; i <= 10_0000_0000; i++) {
    48. sum += i;
    49. }
    50. long end = System.currentTimeMillis();
    51. System.out.println("sum="+sum+" 时间:"+(end-start));
    52. }
    53. //最基本的forkjoin 二分查找拆分任务
    54. //拆分任务 关键在于算法 你自己写
    55. public static void test2(){
    56. long start = System.currentTimeMillis();
    57. ForkJoinPool forkJoinPool = new ForkJoinPool();
    58. ForkJoinTask<Long> task = new ForkJoinTest2(0L, 10_0000_0000L);
    59. Long sum = forkJoinPool.invoke(task);
    60. // ForkJoinTask<Long> submit = forkJoinPool.submit(task);// 提交任务
    61. // Long sum = submit.get();
    62. long end = System.currentTimeMillis();
    63. System.out.println("sum="+sum+" 时间:"+(end-start));
    64. }
    65. public static void test3(){
    66. long start = System.currentTimeMillis();
    67. //jdk8 stream流式计算
    68. long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
    69. long end = System.currentTimeMillis();
    70. System.out.println("sum="+sum+"时间:"+(end-start));
    71. }
    72. }