有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JavaFx TextArea在循环内调用appendText()时冻结

所以我尝试从循环中非常频繁地更新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在数百次循环后停止更新,但在同一时间系统中。出来打印(“数据”);它本该起作用的

    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) 个答案

  1. # 1 楼答案

    这是因为您阻塞了UI线程

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

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