• java并发框架--Fork-Join


    并行计算


    Fork-Join

    关键类

    例子

    ``` package sumTest2; /** * 计算1-10000000的和 * 适用范围:计算不知道计算量大小的计算 */ import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask;

    public class SumTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    ForkJoinPool pool = new ForkJoinPool();

        SumTask task = new SumTask(1,10000000);//大任务
    
        ForkJoinTask<Long> result = pool.submit(task);
    
        //等待结果
    
        do {
            System.out.printf("Main: Thread Count: %d
    ",pool.getActiveThreadCount());//正在运行的线程
            System.out.printf("Main: Paralelism: %d
    ",pool.getParallelism());//并行度
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!task.isDone());
        System.out.println(result.get().toString());
    }
    

    }

    ```java
    package sumTest2;
    
    import java.util.concurrent.RecursiveTask;
    //继承这个可以自动递归
    public class SumTask extends RecursiveTask<Long> {
    
        private int start;
        private int end;
    
        public SumTask(int start, int end) {
            this.start = start;
            this.end = end;
        }
        public static final int  Max= 5;
    
        @Override
        protected Long compute() {
            Long sum = 0L;
            boolean canCompute = (end - start)<= Max;
            if (canCompute){
                for (int i = start; i <= end; i++){
                    sum += i;
                }
            }else{
                int middle = (end + start) / 2;
                SumTask subTask1 = new SumTask(start, middle);
                SumTask subTask2 = new SumTask(middle+1, end);
    
                //invokeAll(subTask1, subTask2);
                subTask1.fork();
                subTask2.fork();
                Long sum1 = subTask1.join();
                Long sum2 = subTask2.join();
                sum = sum1 + sum2;
            }
            return sum;
        }
    }
    
    
    不一样的烟火
  • 相关阅读:
    乐乐的作业
    Spring中配置数据源的5种形式
    乐观锁和悲观锁的区别
    使用Nexus搭建Maven私服
    Maven错误记录
    Maven学习笔记(一)
    Eclipse的SVN插件下载
    SSH整合(Struts2+Spring+Hibernate)
    java.lang.NoClassDefFoundError: org/objectweb/asm/Type
    使用mss2sql将SqlServer转换为Mysql
  • 原文地址:https://www.cnblogs.com/cstdio1/p/12259652.html
Copyright © 2020-2023  润新知