RecursiveTask示例

public class ForkJoinRecursiveTask {

	private final static int MAX_THRESHOLD = 100;
	
	public static void main(String[] args) {
		final ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinTask task = forkJoinPool.submit(new CalculateRecursiveTask(0, 1000));
		try {
			Integer sumResult = task.get();
			System.out.println(sumResult);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings({"serial" })
	private static class CalculateRecursiveTask extends RecursiveTask {
		
		private int start;
		
		private int end;
		
		public CalculateRecursiveTask(int start, int end) {
			this.start = start;
			this.end = end;
		}

		@Override
		protected Integer compute() {
			if (end - start <= MAX_THRESHOLD) {
				return IntStream.rangeClosed(start, end).sum();
			} else {
				int middle = (start + end) / 2;
				CalculateRecursiveTask lTask = new CalculateRecursiveTask(start, middle);
				CalculateRecursiveTask rTask = new CalculateRecursiveTask(middle+1, end);
				lTask.fork();
				rTask.fork();
				return lTask.join() + rTask.join();
			}
		}
	}
}

 

你可能感兴趣的:(JUC)