ForkJoin在JDK1.7出现,并发执行任务!提高效率。大数据了。
大数据:Map Reduce(把大任务拆分为小任务)
里面维护的是双端队列
import java.util.concurrent.RecursiveTask; public class FrokJoinDemo extends RecursiveTask<Long> { private Long s; private Long e; private Long temp = 2L; public FrokJoinDemo(Long s, Long e) { this.s = s; this.e = e; } @Override protected Long compute() { if (e - s < temp) { Long sum = 0L; for (Long i = s; i <= e; i++) { sum += i; } return sum; } else { Long middle = (s + e) / 2;// 中间值 FrokJoinDemo task1 = new FrokJoinDemo(s, middle); task1.fork();// 拆分任务,把任务压如线程队列 FrokJoinDemo task2 = new FrokJoinDemo(middle + 1, e); task2.fork(); return task1.join() + task2.join(); } } }
测试类
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.stream.LongStream; public class ForkJoinTest { public static void main(String[] args) throws Exception { System.out.println("测试计算机配置:"); System.out.println("CPU:"+Runtime.getRuntime().availableProcessors()); System.out.println("Java虚拟机运行内存:"); System.out.println("可用内存总量:"+Runtime.getRuntime().totalMemory()/1024/1024+"M"); System.out.println("=========== 传统方式 ============="); test1(); System.out.println("=========== ForkJoin ============="); test2(); System.out.println("=========== Stream并行流 ============="); test3(); } private static void test1() { long start = System.currentTimeMillis(); Long sum = 0L; for (Long i = 1L; i <= 10_0000_0000L; i++) { sum += i; } long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 时间:" + (end - start)); } private static void test2() throws Exception { long start = System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask<Long> submit = forkJoinPool.submit(new FrokJoinDemo(0L, 10_0000_0000L)); Long sum = submit.get(); long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 时间:" + (end - start)); } private static void test3() { long start = System.currentTimeMillis(); long sum = LongStream.rangeClosed(0, 10_0000_0000L).parallel().reduce(0, Long::sum); long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 时间:" + (end - start)); } }
运行结果对比
测试计算机配置: CPU:8 Java虚拟机运行内存: 可用内存总量:121M =========== 传统方式 ============= sum=500000000500000000 时间:7822 =========== ForkJoin ============= sum=500000000500000000 时间:37865 =========== Stream并行流 ============= sum=500000000500000000 时间:400