• java多线程 -- ForkJoinPool 分支/ 合并框架 工作窃取


    Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总。

    Fork/Join 框架与线程池的区别

    1. 采用 “工作窃取”模式(work-stealing):当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。
    2. 相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程的等待时间,提高了性能。

    ForkJoinPool封装类:

    package com.company;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ForkJoinPool;
    import java.util.concurrent.ForkJoinTask;
    
    public final class ForkJoinPoolUtils {
    
        private static final int CPUS_COUNT = Runtime.getRuntime().availableProcessors();
    
        private ForkJoinPoolUtils(){}
    
    
        public static <T> T executeInDedicatedThreadPool(Callable<T> task){
            return executeInDedicatedThreadPool(task, CPUS_COUNT);
        }
        public static <T> T invokeInDedicatedThreadPool(ForkJoinTask<T> task){
            return new ForkJoinPool(CPUS_COUNT).invoke(task);
        }
    
    
        public static <T> T executeInDedicatedThreadPool(Callable<T> task, int threadsCount){
            try{
                return new ForkJoinPool(threadsCount).submit(task).get();
            }
            catch( ExecutionException execEx ){
                throw new IllegalStateException(execEx);
            }
            catch(InterruptedException interEx ){
                Thread.currentThread().interrupt();
                throw new IllegalStateException(interEx);
            }
        }
    
    }

    使用forkJoinPool Demo:

    package com.company;
    
    import java.time.Duration;
    import java.time.Instant;
    import java.util.concurrent.ForkJoinTask;
    import java.util.concurrent.RecursiveTask;
    
    public class TestForkJoinPool {
    
        public static void main(String[] args) {
            Instant start = Instant.now();
            ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 500000000L);
            Long sum = ForkJoinPoolUtils.invokeInDedicatedThreadPool(task);
            System.out.println(sum);
            Instant end = Instant.now();
            System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//166-1996-10590
        }
    
    }
    
    class ForkJoinSumCalculate extends RecursiveTask<Long> {
    
        private static final long serialVersionUID = -259195479995561737L;
        private long start;
        private long end;
        private static final long THURSHOLD = 10000L;  //临界值
    
        public ForkJoinSumCalculate(long start, long end) {
            this.start = start;
            this.end = end;
        }
    
        @Override
        protected Long compute() {
            long length = end - start;
    
            if (length <= THURSHOLD) {
                long sum = 0L;
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            } else {
                long middle = (start + end) / 2;
                ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
                left.fork(); //进行拆分,同时压入线程队列
                ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
                right.fork(); //
                return left.join() + right.join();
            }
        }
    
    }

    结果:

    125000000250000000
    耗费时间为:204
  • 相关阅读:
    Springboot 中AOP的使用
    ElasticSearch 聚合查询百分比
    ElasticSearch 入门
    elasticsearch 关联查询
    spring data elasticsearch多索引查询
    elasticsearch 拼音+ik分词,spring data elasticsearch 拼音分词
    es同步mysql同步-logstash
    jpa Specification复杂查询
    java Spring boot使用spring反射
    BeautifulSoup学习记录
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/6662339.html
Copyright © 2020-2023  润新知