假如我们要计算从一到1000的和,一般用单线程就可以完成,那么假如我们要计算从1到9999999999999999的和,CPU可能就会扛不住,那么这就需要用多线程去做,JUC下的ForkJoinPool可以很高效地解决此类问题,我们可以先弄一个线程执行1~125的结果,另一个线程执行126~500的结果,以此类推,效率就会增加很多。
下面是代码:
package JUC;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* @Description:
* @Author CHEN
* @Date 2022/7/9 0009
*/
public class ForkTest {
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
try {
System.out.println(pool.submit(new SubTask(1, 1000)).get());
} catch (InterruptedException exception) {
exception.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class SubTask extends RecursiveTask<Integer> {
private int start;
private int end;
public SubTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if((end - start) > 125) {
SubTask subTask1 = new SubTask(start, (start + end) / 2);
subTask1.fork();
SubTask subTask2 = new SubTask((start + end) / 2 + 1, end);
subTask2.fork();
return subTask1.join() + subTask2.join();
} else {
System.out.println(Thread.currentThread().getName() + "start add from " + start +"end" +end);
int result = 0;
for (int i = start; i <= end; i++) {
result += i;
}
return result;
}
}
}
}
运行结果:
ForkJoinPool-1-worker-13start add from 251end375
ForkJoinPool-1-worker-8start add from 126end250
ForkJoinPool-1-worker-15start add from 1end125
ForkJoinPool-1-worker-12start add from 751end875
ForkJoinPool-1-worker-2start add from 376end500
ForkJoinPool-1-worker-10start add from 501end625
ForkJoinPool-1-worker-12start add from 626end750
ForkJoinPool-1-worker-13start add from 876end1000
500500
Process finished with exit code 0
这样一个线程只负责125的计算量,大大提高了效率。