我的问题很简单。
假设我正在执行算法"A star"(使用启发式函数计算下一个访问状态的搜索算法(。
我想在网格中显示更新(我会将其应用于 8 谜题问题(。我应该怎么做?我希望更改清晰可见。但根据我的经验,如果我只是做类似Grid[6].showValue(newValue)
GUI 就会"待机"。
我相信这可以通过多线程来完成(也许?(,但是有没有更简单的方法?
如果可能的话,还有一个非常简单的问题:我想知道在Java(我的IDE是Netbeans(中是否有任何类包含搜索方法,如BFS,DFS和A star?如果是这样,您能否提供指向算法代码的链接(我需要将它们用作代码的基础。我不能直接包含它们。你知道的。。大学作业(。我想这段代码很容易找到,因为Java是一种开源语言。我错了吗?
谢谢
不要在 GUI 线程中进行处理。
如果我们在这里谈论的是 swing,那就是事件调度线程;按照 Swing 中的并发教程中所述使用工作线程。
你应该在单独的线程中进行处理,就像 MДΓΓ БДLL 建议的那样。基本上,您必须在实现 Runnable
的类中实现与搜索相关的代码,该类将类"标记"为线程中的可执行。
为此,您可以使用SwingWorker
:
SwingWorker<Integer[], Void> worker = new SwingWorker<Integer[], Void>() {
public Integer[] doInBackground() {
//do the computation here. This will be executed in a different thread;
//thus allowing the event dispatch thread (=GUI thread) to ensure responsiveness of the UI.
//NEVER update your GUI here since this could cause strange errors that are sometimes hard to track down.
}
public void done() {
try {
Integer[] result = get(); //this is executed in the GUI thread after
//execution if the doInBackground method finished and fetches the result of
//that method. You should update your GUI here.
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (ExecutionException ex) {
ex.printStackTrace();
}
}
}
对于你的第二个答案:很难以这种通用的方式实现一种算法,因为它可用于不同的数据类型,特别是因为你使用的BFS,DFS和A-Star的树可能包含任何类型的数据。我认为您应该在教科书或讲座节点中找到伪代码中的算法;如果没有,请在某处查找并尝试自己实现它。