为什么不是 Swing "thread safe"?

Why is not Swing "thread safe"?

在有关线程的 Java 课的最后几分钟,我们的教授建议我们在开发复杂的基于 Swing 的应用程序时要特别注意,因为 Swing 不是线程安全的。这背后有什么具体原因吗? Swing 由于设计决定或软件限制,线程不安全? 预先感谢您的回答。

Javin Poul 的编程博客Java Revisited has a great blog post关于这个:

Why Swing is not thread-safe in Java?

It's the decision taken by there designer, at that time. Since making an API thread-safe takes a lot of work, and it's often based upon benefit you get. Since GUI screens are mostly updated in response of user action e.g. when user click a button, and since events are handled in the same Event dispatcher thread, it's easy to update GUI on that thread. It's very rare, when an update request for GUI comes from a different thread e.g. may be once a network request is complete or a file is loaded.

即使不是全部,大多数 GUI 工具包都不是线程安全的(Qt、Swing、Winforms...)。创建一个线程安全的 GUI 工具包会增加太多不必要的复杂性。在大多数情况下,创建就足够了 一个快速的事件处理程序。

例如,我们有一个按钮可以计算 从今天起 40 天后的一周中的一天,将摄氏温度转换为华氏温度,或计算所提供值的总和。所有这些操作都可以相当快地计算出来。如果 Swing 是线程安全的,那么这些计算将放在单独的线程中,这显然是一种矫枉过正。因此,我们只将长运行 任务放入线程中,例如刻录 DVD、计算非常复杂的任务、下载大文件等。

看到这个答案: Why are most UI frameworks single threaded?