fork/join - 高飞网
89 人阅读

fork/join

2017-07-28 02:09:46


Java并发——Fork/Join框架 - LaplaceDemon - 博客园



package java7.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		int numberOfProcessors = Runtime.getRuntime().availableProcessors();
		ForkJoinPool pool = new ForkJoinPool(numberOfProcessors);
		int value = 1_00;

		long time1 = System.currentTimeMillis();
		ForkJoinTask<Integer> result = pool.submit(new CountTask(1, value));
		Integer sum = result.get();
		System.out.println(sum + ":1]" + (System.currentTimeMillis() - time1));

		long time2 = System.currentTimeMillis();
		int sum2 = 0;
		for (int i = 1; i <= value; i++) {
			sum2 = CountTask.add(sum, i);
		}
		System.out.println(sum2 + ":2]" + (System.currentTimeMillis() - time2));

	}
}

class CountTask extends RecursiveTask<Integer> {

	private static final long serialVersionUID = 4032729308473196427L;
	private static final int THRESHOLD = 20;// 阈值

	int start, end;

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

	@Override
	protected Integer compute() {
		int sum = 0;
		if (end - start <= THRESHOLD) {// 任务足够小
			for (int i = start; i <= end; i++) {
				sum = add(sum, i);
			}
			// System.out.println(Thread.currentThread().getName() + ":" + start + "," + end);
		} else {
			int mid = (start + end) / 2;
			CountTask leftTask = new CountTask(start, mid);
			CountTask rightTask = new CountTask(mid + 1, end);
			leftTask.fork();
			rightTask.fork();

			int leftSum = leftTask.join();
			int rightSum = rightTask.join();
			sum = leftSum + rightSum;
		}
		return sum;
	}

	public static int add(int a, int b) {
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return a + b;
	}
}


还没有评论!
23.20.166.68