hello java fork/join for java,forkjoin
分享于 点击 33561 次 点评:111
hello java fork/join for java,forkjoin
1,示例
import java.util.concurrent.RecursiveTask;
public class Calculator extends RecursiveTask<Integer> {
private static final int THRESHOLD = 4;
private int start;
private int end;
public Calculator(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 += i;
}
System.err.println(">>>>>>>>");
}else{
int middle = (start + end) /2;
Calculator left = new Calculator(start, middle);
Calculator right = new Calculator(middle + 1, end);
left.fork();
right.fork();
sum = left.join() + right.join();
}
return sum;
}
}
2 运行
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
public class Test {
/**
* @param args
* @throws Exception
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, Exception {
// TODO Auto-generated method stub
ForkJoinPool forkJoinPool = new ForkJoinPool();
Future<Integer> result = forkJoinPool.submit(new Calculator(0, 9));
//new Integer(49995000)
System.err.println(result.get());
相关文章
- 暂无相关文章
用户点评