【发布时间】:2014-11-26 07:28:09
【问题描述】:
我试图理解 ForkJoinPools,所以我做了以下简单的测试类。不幸的是,它没有达到我的预期。谁能指出我哪里出错了?
import java.util.*;
import java.util.concurrent.*;
public class UtilsShowcase {
public static void main(String[] args){
final UtilsShowcase us = new UtilsShowcase();
us.run();
}
public void run(){
forkJoinPoolDemo();
}
public void forkJoinPoolDemo(){
final ForkJoinPool forkJoinPool = new ForkJoinPool();
Future<String> result = forkJoinPool.submit(new MyTask(8));
try {
result.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class MyTask extends RecursiveTask<String> {
final long num;
MyTask(long number){
this.num = number;
}
protected String compute(){
System.out.println("In compute with number of "+num);
if (num > 1){
System.out.println("Generating two more tasks with number of "+num/2);
(new MyTask(num/2)).fork();
(new MyTask(num/2)).fork();
}
return "Returning from a number "+num;
}
}
}
我希望它从数字 8 开始,然后为数字 4 启动两个任务,为数字 2 启动 4 个任务,为数字 1 启动 8 个任务。相反,它打印出:
In compute with number of 8
Generating two more tasks with number of 4
In compute with number of 4
Generating two more tasks with number of 2
In compute with number of 4
Generating two more tasks with number of 2
In compute with number of 2
Generating two more tasks with number of 1
In compute with number of 2
Generating two more tasks with number of 1
In compute with number of 1
In compute with number of 2
In compute with number of 1
它的一部分是正确的 - 它打印出 2 个数字 4 任务,但只有 3 个数字 2(而不是 4 个)和 2 个数字 1(而不是 8 个!)
非常感谢!
【问题讨论】:
-
子任务被分叉,但从未加入...
-
使用join结果更有趣ideone.com/BIjFjQ
-
谢谢!是的,我只是想先让我的头绕过叉子。现在也在查看连接部分。
标签: java concurrency