【发布时间】:2015-04-29 14:59:15
【问题描述】:
我正在尝试实现一个 Fork Join Pool,它将获取一个节点的子节点并同时探索它们。但是我认为我的 fork join pool 执行了线程然后关闭太快,导致线程停止执行?
到目前为止,我有这个代码:
主要方法:
while (!(pqOpen.IsEmpty()))
{
tempVertex = pqOpen.GetNextItem();
if (tempVertex.city == endLocation.city)
{
resetVertex();
return tempVertex;
}
else
{
ForkJoinPool forkJoinPool = new ForkJoinPool(tempVertex.neighbors.GetNoOfItems());
for (int i = 0; i < tempVertex.neighbors.GetNoOfItems(); i++) //for each neighbor of tempVertex
{
forkJoinPool.execute(new NeighbourThread(tempVertex, allVertices, routetype, pqOpen, i, endLocation));
}
forkJoinPool.shutdown();
}
}
return null;
}
这是我运行的课程:
public class NeighbourThread extends RecursiveAction {
Vertex tempVertex, endLocation;
VertexHashMap allVertices;
int routetype, i;
PriorityQueue pqOpen;
public NeighbourThread(Vertex tempVertex, VertexHashMap allVertices, int routetype, PriorityQueue pqOpen, int i, Vertex endLocation)
{
this.allVertices = allVertices;
this.routetype = routetype;
this.tempVertex = tempVertex;
this.pqOpen = pqOpen;
this.i = i;
this.endLocation = endLocation;
}
@Override
public void compute() {
Edge currentRoad = tempVertex.neighbors.GetItem(i);
Vertex vertexNeighbour = allVertices.GetValue(currentRoad.toid);
if (vertexNeighbour.inClosed)//
return null;
if ((!vertexNeighbour.inOpen) || temp_g_score < vertexNeighbour.getTentativeDistance())
{
vertexNeighbour.from = tempVertex;
vertexNeighbour.setTentativeDistance(temp_g_score);
// if neighbor isn't in open set, add it to open set
if (!vertexNeighbour.inOpen)
{
vertexNeighbour.inOpen = true;
pqOpen.AddItem(vertexNeighbour);
}
}
}
我已经删除了 compute() 中的大部分代码,因为我认为它与问题无关。
我认为问题在于 forkJoinPool.shutdown() 行在已创建的线程完成执行之前被执行。 有什么方法可以确保线程在我循环回到 while 循环的顶部之前完成?
【问题讨论】:
-
我对您的代码没有深入了解,但是在提出问题时,最好清楚地说明问题所在。我可以推断您的问题是执行任务和关闭时之间存在竞争,但不完全确定。例如“我提交的所有任务都没有被执行”等等......
-
嗨,John,我想您可能没有阅读我帖子的底部,所以我会对其进行编辑,并确保将问题描述放在顶部!
-
关于代码质量的旁注:用通用术语(如“计算”)命名一个方法……然后在该单一方法中做许多不同的事情……导致代码难以维护。见这里:java.dzone.com/articles/single-responsibility
-
我看不到您的任务在哪里执行任何递归。也就是说,只有“主要方法”将任何任务添加到
ForkJoinPool。是对的吗?我的意思是,你为什么使用ForkJoinPool而没有fork()或join()?
标签: java concurrency fork-join forkjoinpool