木頭人的gravatar頭像
木頭人2018-08-21 10:52:46

java并行執行任務的框架Fork/Join的使用實例

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @Auther: jack
 * @Date: 2018/7/23 19:50
 * @Description:
 *            Fork/Join框架是Java 7提供的一個用于并行執行任務的框架,
 *            是一個把大任務分割成若干個小任務,最終匯總每個小任務結果后得到大任務結果的框架
 */
public class ForkJoinCalculator extends RecursiveTask<Long> {
    private long start;
    private long end;
    private static final long THRESHOLD=10000;

    public ForkJoinCalculator(long start,long end){
        this.start=start;
        this.end=end;
    }

    @Override
    protected Long compute() {
        if(end-start<THRESHOLD){
            long sum=0;
            for(long i=start;i<=end;i++){
                sum+=i;
            }
            return sum;
        }
        else{
            //大于臨界值拆分任務
            long mid=(start+end)/2;

            ForkJoinCalculator forkJoinCalculator=new ForkJoinCalculator(start,mid);
            forkJoinCalculator.fork();
            ForkJoinCalculator forkJoinCalculator2=new ForkJoinCalculator(mid+1,end);
            forkJoinCalculator2.fork();

            return forkJoinCalculator.join()+forkJoinCalculator2.join();
        }

    }

    public static void main(String[] args) {
        //jdk7的fork,join使用
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinTask = forkJoinPool.submit(new ForkJoinCalculator(1, 10000000L));
        try{
            System.out.println(forkJoinTask.get());
        }catch (Exception e){
          e.printStackTrace();
        }
        Long sum=forkJoinPool.invoke(new ForkJoinCalculator(1, 10000000L));
        System.out.println(sum);
        long end=System.currentTimeMillis();
        System.out.println("總共耗時為:"+(end-start));

        //jdk8的并行流
        start = System.currentTimeMillis();
        sum=LongStream.rangeClosed(1,10000000L).parallel().reduce(0,Long::sum);
        System.out.println(sum);
        end=System.currentTimeMillis();
        System.out.println("總共耗時為:"+(end-start));
    }
}

運行結果:

java并行執行任務的框架Fork/Join的使用實例


打賞

頂部客服微信二維碼底部
>掃描二維碼關注最代碼為好友掃描二維碼關注最代碼為好友
北京