Java:Swing 库和线程安全 [英] Java: Swing Libraries & Thread Safety

查看:38
本文介绍了Java:Swing 库和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常听到有人批评 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 ?

推荐答案

  1. 永远不要为响应按钮、事件等而执行长时间运行的任务,因为这些都在事件线程上.如果您阻止事件线程,整个 GUI 将完全没有响应,从而导致用户非常生气.这就是为什么 Swing 看起来又慢又硬的原因.

  1. 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.

使用线程、执行器和 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 调试技术 和智能的外观和感觉(如 Substance,它检查 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 工作示例:Palantir Technologies.注意:我不为他们工作,只是一个很棒的挥杆的例子.可惜没有公开演示......他们的博客也很好,稀疏,但很好

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 库和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆