[英]Search algorithms (DFS,BFS,A star etc.). How to update the GUI (with updated state) without “freezing”?
我的問題很簡單。
假設我正在執行算法“A star”(使用啟發式函數計算下一個要訪問的狀態的搜索算法)。
我想在網格中顯示更新(我將它應用於8-puzzle問題)。 我該怎么辦? 我希望變化清晰可見..但根據我的經驗,如果我只是執行Grid[6].showValue(newValue)
之類的操作,GUI將只是“待命”。
我敢肯定這可以用多線程完成(也許?)但是有沒有更簡單的方法?
如果可能的話還有一個非常簡單的問題:我想知道在Java(我的IDE是Netbeans)中是否有任何類包含搜索方法,如BFS,DFS和A star? 如果是這樣,你能提供一個算法代碼的鏈接(我需要使用它們作為我的代碼的基礎..我不能直接包括它們..你知道..大學任務)。 我想這個代碼很容易找到,因為Java是一種開源語言。 我錯了嗎?
非常感謝你
不要在GUI線程中進行處理。
如果我們在這里談論搖擺 ,那就是Event Dispatch Thread; 使用工作線程,如Swurrency中的Concurrency教程中所述 。
您應該在單獨的線程中進行處理,如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的樹可能包含任何類型的數據。 我認為你應該在教科書或講座節點中找到偽代碼的算法; 如果沒有,請在某處查找並嘗試自己實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.