问题描述
我经常听到批评Swing库中缺乏线程安全性。然而,我不确定我在自己的代码中会做什么可能导致问题:
I've often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues:
在什么情况下Swing不是线程安全的事实进入玩?
In what situations does the fact Swing is not thread safe come into play ?
我应该主动避免做什么?
What should I actively avoid doing ?
推荐答案
-
永远不要执行长时间运行的任务以响应事件线程上的按钮,事件等。如果您阻止事件线程,整个GUI将完全没有响应,导致真正生气的用户。这就是为什么Swing看起来很慢而且很脆弱的原因。
Never do long running tasks in response to a button, event, etc as these are on the event thread. If you block the event thread, the ENTIRE GUI will be completely unresponsive resulting in REALLY pissed off users. This is why Swing seems slow and crusty.
使用Threads,Executors和SwingWorker来运行不在EDT上的任务(事件调度线程)。
Use Threads, Executors, and SwingWorker to run tasks NOT ON THE EDT ( event dispatch thread).
不要在EDT之外更新或创建小部件。几乎可以在EDT之外进行的唯一调用就是Component.repaint()。使用SwingUtilitis.invokeLater确保在EDT上执行某些代码。
Do not update or create widgets outside of the EDT. Just about the only call you can do outside of the EDT is Component.repaint(). Use SwingUtilitis.invokeLater to ensure certain code executes on the EDT.
使用和智能外观(如,用于检查违反EDT的情况)
Use EDT Debug Techniques and a smart look and feel (like Substance, which checks for EDT violation)
如果您遵守这些规则,Swing可以制作一些非常有吸引力和响应的GUI
If you follow these rules, Swing can make some very attractive and RESPONSIVE GUIs
一些真正令人敬畏的Swing UI工作的例子:。注意:我不为他们工作,只是一个令人敬畏的挥杆的例子。羞耻没有公开演示...他们的也很好,很稀疏但很好
An example of some REALLY awesome Swing UI work: Palantir Technologies. Note: I DO NOT work for them, just an example of awesome swing. Shame no public demo... Their blog is good too, sparse, but good
这篇关于Java:Swing Libraries&线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!