ForkJoin demo 示例

package com.aop8.forkjoin;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

import org.junit.Test;

class ForkJoinSumCalulate extends RecursiveTask<Long> {

	private Long start;
	private Long end;

	public static final int threshold = 5;// 临界值

	public ForkJoinSumCalulate(Long start, Long end) {
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		Long length = end - start;
		if (length <= threshold) {
			Long sum = 0L;
			for (Long i = start; i <= end; i++) {
				sum += i;
			}
			return sum;
		} else {
			Long middle = (start + end) / 2;

			ForkJoinSumCalulate left = new ForkJoinSumCalulate(start, middle);
			left.fork();
			ForkJoinSumCalulate right = new ForkJoinSumCalulate(middle + 1, end);
			right.fork();
			return left.join() + right.join();
		}
	}
}

public class Main {

	//1、ForkJoin实现计算
	public static void main(String[] args) {
		ForkJoinPool pool = new ForkJoinPool();
		ForkJoinSumCalulate task = new ForkJoinSumCalulate(1l, 100L);
		Long sum = pool.invoke(task);
		System.out.println(sum);
	}
	
	//2、普通的for循环
	@Test
	public void test1() {
		Instant start=Instant.now();
		Long sum=0l;
		for (Long i = 0L; i <= 100L; i++) {
			sum+=i;
		}
		System.out.println(sum);
		Instant end=Instant.now();
		System.out.println("耗时:"+Duration.between(start, end).toMillis());
	}
	
	
	//3、使用jdk8的API
	@Test
	public void test2() {
		Instant start=Instant.now();
		Long sum=LongStream.rangeClosed(0l, 100L)//
				.parallel()//
				.reduce(0, Long::sum);//
		
		System.out.println(sum);
		Instant end=Instant.now();
		System.out.println("耗时:"+Duration.between(start, end).toMillis());
	}
}

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/87859560