invokeLater vs invokeAndWait with JTextArea

2019-06-12 16:22发布

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?

Thanks

1条回答
Bombasti
2楼-- · 2019-06-12 16:47

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.

查看更多
登录 后发表回答