package com.famous.thread.util;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
/**
* fork join framwork test
*
* @author zhenglong fork/join任务应该是纯内存算法,而没有I/O操作
* 此外,应该尽可能避免通过共享状态来进行任务间的通信,因为这通常意味着加锁会被执行。理想情况下,
* 仅当一个任务fork另一个任务或一个任务join另一个任务时才进行任务通信。
*/
public class ForkJoinDemo {
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool();
CountTask task = new CountTask(1, 4);
Future<Integer> result = forkJoinPool.submit(task);
try {
System.out.println(result.get());
} catch (Exception e) {
}
}
}
class CountTask extends RecursiveTask<Integer> {
private int min;
private int max;
private int threadCount;
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getThreadCount() {
return threadCount;
}
public void setThreadCount(int threadCount) {
this.threadCount = threadCount;
}
public CountTask(int min, int max) {
this.min = min;
this.max = max;
}
/**
*
*/
private static final long serialVersionUID = 4618283439406101422L;
@Override
protected Integer compute() {
int sum = 0;
boolean canCompute = (max - min) <= threadCount;
// 小于
if (canCompute) {
for (int i = min; i <= max; i++)
sum += i;
} else {
int mid = (max + min) / 2;
CountTask leftTask = new CountTask(min, mid);
CountTask rightTask = new CountTask(mid + 1, max);
// 执行子任务
leftTask.fork();
rightTask.fork();
int leftResult = (int) leftTask.join();
int rightResult = (int) rightTask.join();
sum = leftResult + rightResult;
}
return sum;
}
}