gpt4 book ai didi

java - 为什么 ForkJoinPool 没有运行所有任务?

转载 作者:行者123 更新时间:2023-11-30 03:39:21 24 4
gpt4 key购买 nike

我试图理解 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!)

非常感谢!

最佳答案

啊,在这里回答我自己的问题。

意识到主线程可能在其他线程完成所有工作之前退出,并且由于 ForkJoinPool 是一个守护进程,它只是默默地结束了。如果我添加

            try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

在方法 forkJoinPoolDemo 的末尾,我得到了我期望的结果:

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 2
Generating two more tasks with number of 1
In compute with number of 4
In compute with number of 1
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 1
In compute with number of 1
In compute with number of 1
In compute 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 1

恢复理智:-)

关于java - 为什么 ForkJoinPool 没有运行所有任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com