就是把一个烧饼分为四块。
单核的时候路子转烤烧饼肯定没有一个一个烤烧饼快,因为切换消耗资源
现在是多核了就没有这个问题了。
多核是多个火炉,但是一个烧饼其他的火苗就全浪费了。
Fork/join就是将一个烧饼切位四份,多核cpu,多个火苗。
烤完之后四份合为一个。
单核就没有必要使用fork join了。
----------------------------------------------------------------------------------------------------------------------------
-------
计算1+2+3+4+5+。。。。。。。+100
分开分为50个小任务。
继承关系图。
框架给我们实现的类:
package com.roocon.thread.tc1;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
public class Demo extends RecursiveTask<Integer> {
private int begin;
private int end;
public Demo(int begin, int end) {
this.begin = begin;
this.end = end;
}
@Override
protected Integer compute() {
System.out.println(Thread.currentThread().getName() + " ... ");
int sum = 0;
// 拆分任务
if (end - begin <= 2) {//两个数或者三个数
// 计算
for (int i = begin; i <= end; i++) {
sum += i;
}
} else {
// 拆分
Demo d1 = new Demo(begin, (begin + end) / 2);//任务折半
Demo d2 = new Demo((begin + end)/2 + 1, end);
// 执行任务
d1.fork();
d2.fork();
Integer a = d1.join();
Integer b = d2.join();
sum = a + b;
}
return sum;
}
public static void main(String[] args) throws Exception {
ForkJoinPool pool = new ForkJoinPool(3);//new一个池子
Future<Integer> future = pool.submit(new Demo(1, 1000000000));//指定任务注意有返回值的,任务就是1-1000000000的和
System.out.println("....");
System.out.println("计算的值为:" + future.get());
}
}
学习的知识点:可以提高cpu的利用率能够提高多核的执行性能。
-------------------------------------------------tc1----------------------------------------------------------------