package ThreadTest.com.jk.ForkJoinTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; import java.util.concurrent.atomic.AtomicInteger; /** * 计算给定函数 y=1/x 在定义域 [1,100]上与X轴围成的面积,计算步长0.01 * Created by lizq on 2019/5/16. */ public class AreaCalc { private static final double MAX = 0.01; static class MyForkJoinTask extends RecursiveTask<Double> { private static AtomicInteger num = new AtomicInteger(); private static final int step = 10; // 子任务开始计算的值 private double startValue; // 子任务结束计算的值 private double endValue; public MyForkJoinTask(double startValue, double endValue) { this.startValue = startValue; this.endValue = endValue; } @Override protected Double compute() { // 如果条件成立,说明这个任务所需要计算的数值分为足够小了 double totalValue = 0; if (endValue - startValue <= MAX) { totalValue = (endValue - startValue) * (2.0 / (startValue + endValue)); System.out.println(num.incrementAndGet() + " : 开始计算的部分:startValue = " + startValue + ";endValue = " + endValue + "; sum = " + totalValue); return totalValue; } // 否则再进行任务拆分,拆分成10个子任务 else { double stepVal = (endValue - startValue) / step; for (int i = 0; i < step; i++) { MyForkJoinTask subTask1 = new MyForkJoinTask(startValue + i * stepVal, startValue + (i + 1) * stepVal); subTask1.fork(); totalValue += subTask1.join(); } return totalValue; } } } public static void main(String[] args) { // 这是Fork/Join框架的线程池 ForkJoinPool pool = new ForkJoinPool(); ForkJoinTask<Double> taskFuture = pool.submit(new MyForkJoinTask(1, 100)); try { Double result = taskFuture.get(); System.out.println("result = " + result + " count " + MyForkJoinTask.num.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(System.out); } } } 运行结果:
使用JAVA的forkjoin框架计算给定函数 y=1/x 在定义域 [1,100]上与X轴围成的面积,计算步长0.01
最新推荐文章于 2022-10-29 10:09:15 发布