所以我试图从循环非常频繁地更新文本区域
// 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);
}
潇潇雨雨
相关分类