在循环内调用appendText()时JavaFx TextArea卡住

标签 java javafx concurrency javafx-2

所以我尝试从循环中非常频繁地更新 TextArea

// This code makes the UI freez and the textArea don't get updated
for(int i = 0; i < 10000; i++){
    staticTextArea.appendText("dada \n");
}

我还尝试实现一个 BlockingQueue 来创建更新 TextArea 的任务,这解决了 UI 的卡住问题,但 TextArea 在数百次循环后停止更新,但同时 System.out.print("dada\n");正常工作。

    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);
    }

最佳答案

发生这种情况是因为您阻塞了 UI 线程。

JavaFX 提供 Platform 类,该类公开 runLater 方法。 该方法可用于在 JavaFX 应用程序线程(与 UI 线程不同)上运行长时间运行的任务。

final Runnable appendTextRunnable = 
      () -> {
         for (int i = 0; i < 10000; i++) {
            staticTextArea.appendText("dada \n");
         }
      };

Platform.runLater(appendTextRunnable);

关于在循环内调用appendText()时JavaFx TextArea卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081931/

相关文章:

java - 如何使用 Apache Commons Compress 将文件附加到 .tar 存档?

java - 如何将 LocalDate 与绑定(bind)一起使用

java - 这个简单的代码应该会产生死锁,但事实并非如此

google-apps-script - 是否可以在 Apps Script 中获取新的 Google 幻灯片演示数据?

java - 使用java远程登录linux系统

java - 读取多个.txt文件并将信息写入数组

java - 如何将 JComboBox 项目映射到其对应的 ID?

java - 动态添加的 View 不适合 Pane

animation - JavaFX : How to detect if a key is being held down?

concurrency - 并发和条件信号分配 (VHDL)