使用Fork/Join分割合并任务

import org.apache.commons.lang3.time.StopWatch;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask {
    int start = 0;
    int end = 0;
    // fork的阈值,即start,end相差大于2的时候,进行fork操作
    int threshold = 2;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static int sum(int start, int end) {
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;

            // 让当前线程睡5秒,模拟某个耗时操作
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return sum;
    }

    @Override
    protected Integer compute() {
        if (end - start <= threshold) {
            return sum(start, end);
        } else {
            int middle = (end + start) / 2;
            CountTask left = new CountTask(start, middle);
            CountTask right = new CountTask(middle + 1, end);
            left.fork();
            right.fork();

            int leftResult = left.join();
            int rightResult = right.join();
            return leftResult + rightResult;
        }
    }

    public static void main(String[] args) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future task = forkJoinPool.submit(new CountTask(1, 6));
        System.out.println("ForkJoin执行结果:" + task.get());

        stopWatch.stop();
        System.out.println("ForkJoin执行耗时:" + stopWatch.getTime() + "ms");

        stopWatch.reset();
        stopWatch.start();

        System.out.println("单线程顺序执行结果:" + sum(1, 6));

        stopWatch.stop();
        System.out.println("单线程顺序执行耗时:" + stopWatch.getTime() + "ms");
    }
}

执行的结果:

ForkJoin执行结果:21
ForkJoin执行耗时:15016ms
单线程顺序执行结果:21
单线程顺序执行耗时:30016ms

如果不模拟耗时操作的情况,执行的结果如下:

ForkJoin执行结果:21
ForkJoin执行耗时:15ms
单线程顺序执行结果:21
单线程顺序执行耗时:0ms

可以看出,在执行耗时操作的时候,ForkJoin方式性能的优势比较明显。而执行非耗时操作的时候,单线程的执行几乎不耗时,而ForkJoin方式有15ms,应该主要是线程创建和销毁的时间开销。

你可能感兴趣的:(使用Fork/Join分割合并任务)