subtask.fork()返回ForkJoinTask<Int>
对象后会发生什么?之后,compute()方法被调用了很多次,但是从何处以及如何调用?
我是Java的新手,正在尝试学习fork/join框架的概念。我在网上看到下面的代码。我知道在阅读Java API之后subtask.fork()
返回了ForkJoinTask<V>
对象,在这种情况下,它是ForkJoinTask<Int>
。我不明白的是那之后会发生什么?输出表明compute()
方法此后已被多次调用,但是从何处以及如何调用?
public class MyRecursiveAction extends RecursiveAction {
public static void main(String[] args) {
MyRecursiveAction mra1 = new MyRecursiveAction(100);
ForkJoinPool fjp1 = new ForkJoinPool();
fjp1.invoke(mra1);
}
private long workLoad = 0;
public MyRecursiveAction(long workLoad) {
this.workLoad = workLoad;
}
@Override
protected void compute() {
//if work is above threshold, break tasks up into smaller tasks
if(this.workLoad > 16) {
System.out.println("Splitting workLoad : " + this.workLoad);
List<MyRecursiveAction> subtasks =
new ArrayList<MyRecursiveAction>();
subtasks.addAll(createSubtasks());
for(RecursiveAction subtask : subtasks){
subtask.fork();
}
} else {
System.out.println("Doing workLoad myself: " + this.workLoad);
}
}
private List<MyRecursiveAction> createSubtasks() {
List<MyRecursiveAction> subtasks =
new ArrayList<MyRecursiveAction>();
MyRecursiveAction subtask1 = new MyRecursiveAction(this.workLoad / 2);
MyRecursiveAction subtask2 = new MyRecursiveAction(this.workLoad / 2);
subtasks.add(subtask1);
subtasks.add(subtask2);
return subtasks;
}
}
输出:
Splitting workLoad : 100
Splitting workLoad : 50
Splitting workLoad : 50
Splitting workLoad : 25
Doing workLoad myself: 12
Doing workLoad myself: 12
Splitting workLoad : 25
Doing workLoad myself: 12
Doing workLoad myself: 12
Splitting workLoad : 25
Doing workLoad myself: 12
Splitting workLoad : 25
Doing workLoad myself: 12
Doing workLoad myself: 12
Doing workLoad myself: 12
最佳答案
您需要调用invokeAll以便将您的工作分为两部分,而不是手动进行,然后将创建2个新线程来“计算”您的结果,然后,如果它不够小,那么将创建2个新线程,依此类推。
您无法预测线程将以什么顺序执行,因此每次运行此代码时,消息顺序都会有所不同。
public class MyRecursiveAction extends RecursiveAction {
public static void main(String[] args) {
MyRecursiveAction mra1 = new MyRecursiveAction(100);
ForkJoinPool fjp1 = new ForkJoinPool();
fjp1.invoke(mra1);
}
private long workLoad = 0;
public MyRecursiveAction(long workLoad) {
this.workLoad = workLoad;
}
@Override
protected void compute() {
//if work is above threshold, break tasks up into smaller tasks
if(this.workLoad > 16) {
System.out.println("Splitting workLoad : " + this.workLoad);
invokeAll(new MyRecursiveAction(this.workLoad / 2), new MyRecursiveAction(this.workLoad / 2));
} else {
System.out.println("Doing workLoad myself: " + this.workLoad);
}
}
}
Java doc of ForkJoinTask