Fork/Join框架:在必要的情况下,将一个大任务,进行拆分(fork) 成若干个子任务(拆到不能再拆,这里就是指我们制定的拆分的临界值),再将一个个小任务的结果进行join汇总。
采用juc包的fork/join框架
public class ForkJoinWork extends RecursiveTask<Long> { private Long start;//起始值 private Long end;//结束值 public static final Long critical = 100000L;//临界值 public ForkJoinWork(Long start, Long end) { this.start = start; this.end = end; } @Override protected Long compute() { //判断是否是拆分完毕 Long lenth = end - start; if(lenth<=critical){ //如果拆分完毕就相加 Long sum = 0L; for (Long i = start;i<=end;i++){ sum += i; } return sum; }else { //没有拆分完毕就开始拆分 Long middle = (end + start)/2;//计算的两个值的中间值 ForkJoinWork right = new ForkJoinWork(start,middle); right.fork();//拆分,并压入线程队列 ForkJoinWork left = new ForkJoinWork(middle+1,end); left.fork();//拆分,并压入线程队列 //合并 return right.join() + left.join(); } } }
public class ForkJoinWorkTest { public static void main(String[] args) { test(); test2(); test3(); } public static void test() { //ForkJoin实现 long l = System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool();//实现ForkJoin 就必须有ForkJoinPool的支持 ForkJoinTask<Long> task = new ForkJoinWork(0L,1000000000L);//参数为起始值与结束值 Long invoke = forkJoinPool.invoke(task); long l1 = System.currentTimeMillis(); System.out.println("ForkJoin实现 result = " + invoke+" time: " + (l1-l)); //result = 500000000500000000 time: 7422 } public static void test2(){ //普通线程实现 Long x = 0L; Long y = 1000000000L; long l = System.currentTimeMillis(); for (Long i = 0L; i <= y; i++) { x+=i; } long l1 = System.currentTimeMillis(); System.out.println("单线程 result = " + x+" time: " + (l1-l)); //result = 500000000500000000 time: 8274 } public static void test3(){ //Java 8 并行流的实现 long l = System.currentTimeMillis(); long reduce = LongStream.rangeClosed(0, 1000000000L).parallel().reduce(0, Long::sum); long l1 = System.currentTimeMillis(); System.out.println("Java8并行流 result = " + reduce+" time: " + (l1-l)); //result = 500000000500000000 time: 855 } }