gpt4 book ai didi

java - 多线程和递归一起

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:06 25 4
gpt4 key购买 nike

我有以深度优先方式处理树结构的递归代码。代码基本上是这样的:

function(TreeNode curr) 
{
if (curr.children != null && !curr.children.isEmpty())
{
for (TreeNode n : curr.children)
{
//do some stuff
function(n);
}
}
else
{
//do some other processing
}
}

我想使用线程来加快完成速度。大部分时间都花在遍历上,所以我不想只创建一个线程来处理“其他处理”,因为它不需要那么长时间。我想我想在“做一些事情”时 fork 线程,但那将如何工作?

最佳答案

Fork/Join framework 是个好案例它将包含在 Java 7 中。作为与 Java 6 一起使用的独立库,可以下载它 here .

像这样:

public class TreeTask extends RecursiveAction {
private final TreeNode node;
private final int level;

public TreeTask(TreeNode node, int level) {
this.node = node;
this.level = leve;
}

public void compute() {
// It makes sense to switch to single-threaded execution after some threshold
if (level > THRESHOLD) function(node);

if (node.children != null && !node.children.isEmpty()) {
List<TreeTask> subtasks = new ArrayList<TreeTask>(node.children.size());
for (TreeNode n : node.children) {
// do some stuff
subtasks.add(new TreeTask(n, level + 1));
}
invokeAll(subtasks); // Invoke and wait for completion
} else {
//do some other processing
}
}
}

...
ForkJoinPool p = new ForkJoinPool(N_THREADS);
p.invoke(root, 0);

fork/join 框架的关键点是工作窃取——在等待子任务完成时线程执行其他任务。它允许您以直接的方式编写算法,同时避免线程耗尽的问题,因为使用 ExecutorService 的天真方法会遇到。

关于java - 多线程和递归一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5517413/

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