首页 > 代码库 > hello java fork/join for java
hello java fork/join for java
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());
hello java fork/join for java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。