invokeLater vs invokeAndWait with JTextArea [英] invokeLater vs invokeAndWait with JTextArea
问题描述
我有一个在多个线程上运行的 Swing 应用程序,我在 EDT 上创建了 Swing 组件.Executor 启动线程,在某个时刻将文本插入 JTextArea.但是,与 InvokeAndWait 不同,InvokeLater 并不总是执行附加操作.正如我所收集的,它是异步的、非阻塞的,但仍然应该进行附加.怎么可能?
I have a Swing application that runs on multiple threads, I created the Swing components on the EDT. An Executor launches threads that insert text to the JTextArea at some point. However, InvokeLater doesn't always do the appending, unlike InvokeAndWait. As I gathered it's aynchronous, non-blocking, but still should do the appending. How can it be?
谢谢
推荐答案
使用 EventQueue.invokeLater()
从另一个线程更新组件的模型是一个必要——但是不足够——正确同步的条件.您仍然需要同步对任何共享数据的访问.在这个示例中,display()
参数s
是一个final
对 immutable String
的引用;它可以在 display()
中安全访问,无需进一步同步.如果您有对 可变 对象的 final
引用,请考虑使用 线程安全集合.您可以使用此处中引用的方法之一查找违规情况.或者,考虑一个 SwingWorker
托管后台任务,例如示例.
Using EventQueue.invokeLater()
to update a component's model from another thread is a necessary—but not sufficient—condition for correct synchronization. You are still required to synchronize access to any shared data. In this example, the display()
parameter s
is a final
reference to an immutable String
; it can be accessed safely in display()
without further synchronization. If you have a final
reference to a mutable object, consider a thread-safe collection. You can look for violations using one of the approaches cited here. Alternatively, consider a SwingWorker
to host the background task, for example.
这篇关于invokeLater vs invokeAndWait with JTextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!