所以我試圖從循環(huán)非常頻繁地更新文本區(qū)域// This code makes the UI freez and the textArea don't get updatedfor(int i = 0; i < 10000; i++){ staticTextArea.appendText("dada \n");}我還嘗試實現(xiàn)一個BlockingQueue來創(chuàng)建更新TextArea的任務(wù),這解決了UI的凍結(jié)問題,但TextArea在大約一百個循環(huán)后停止更新,但同時System.out.print(“dada \n”);按預(yù)期工作。 private static final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100); private static Thread mainWorker; private static void updateTextArea() { for(int i = 0 ; i < 10000; i++) { addJob(() -> { staticTextArea.appendText("dada \n"); System.out.print("dada \n"); }); } } private static void addJob(Runnable t) { if (mainWorker == null) { mainWorker = new Thread(() -> { while (true) { try { queue.take().run(); } catch (InterruptedException e) { e.printStackTrace(); } } }); mainWorker.start(); } queue.add(t); }
1 回答

瀟瀟雨雨
TA貢獻(xiàn)1833條經(jīng)驗 獲得超4個贊
發(fā)生這種情況是因為你阻止了 UI 線程。
JavaFX 提供了該類,該類公開了該方法。該方法可用于在 JavaFX 應(yīng)用程序線程(與 UI 線程不同)上運行長時間運行的任務(wù)。PlatformrunLater
final Runnable appendTextRunnable =
() -> {
for (int i = 0; i < 10000; i++) {
staticTextArea.appendText("dada \n");
}
};
Platform.runLater(appendTextRunnable);
添加回答
舉報
0/150
提交
取消