我有一个多线程 Java Swing 应用程序。
多个线程将通过 textArea.append("something")
写入 JTextArea
来调用该方法。我应该这样包装吗:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
textArea.append("something");
}
});
或者它只是一个内容更新,Swing 会自己做正确的线程?
最佳答案
一般来说,您对 Swing 所做的任何更新,尤其是任何更改控件状态或布局的操作,都应该在 Swing 线程中完成。
在这种情况下,您完全正确,将每个更新包装到 invokeLater
中是执行此操作的正确方法。您可以尝试更新您自己的队列或类似的队列,但是当 Swing 已经提供了您需要的功能时,使用它是有意义的。
请参阅 JTextArea
文档:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html
它说的地方
Warning: Swing is not thread safe. For more information see Swing's Threading Policy.
它说的地方:
In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.
JTextArea#append
方法中没有任何文档表明可以安全地从其他线程使用。
关于Java Swing多线程访问JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065729/