Why is not Swing “thread safe”? [closed]

风格不统一 提交于 2019-12-25 07:50:22

问题


In the final minutes of a Java lesson about threads, our professor suggested us to pay specific attention when developing complex Swing-based applications, since Swing is not thread-safe. Is there any specific reason behind this? Swing is not thread safe due to a design decision, or due to software limitations? Thanks in advance for the answer.


回答1:


Javin Poul's programming blog Java Revisited has a great blog post about this:

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.




回答2:


Most, if not all, GUI toolkits are not thread-safe (Qt, Swing, Winforms...). Creating a thread-safe GUI toolkit would add too much unneccesary complexity. In most cases, it is sufficient to create a quick event handler.

For instance, we have a button that calculates a week day 40 days from today, converts Celsius temperature to Fahrenheit, or computes the sum of provided values. All these operations can be calculated fairly quickly. If Swing was thread-safe, these calculations would be placed inside separate threads, which would be clearly an overkill. So instead of this, we put only long-running tasks into threads, such as burning a DVD, calculating a very complex task, downloading a huge file etc.

See this answer: Why are most UI frameworks single threaded?



来源:https://stackoverflow.com/questions/39306022/why-is-not-swing-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!