问题描述
在Swing中,由于GUI组件不是线程安全的,因此该GUI应该仅由EDT进行更新.
In Swing, the GUI is supposed to be updated by the EDT only, since the GUI components are not thread safe.
我的问题是,如果我有除EDT之外的单个线程专用于更新特定组件,并且我程序中的任何其他线程都不能访问此组件,那么只能使用该专用线程吗? ?在我的情况下,我有一个JTable
,一个线程从网络接收信息并更新该表(不使用EventQueue.invokeLater
).所有其他组件均从EDT更新.到目前为止,我还没有发现任何问题,我想知道最终是否会出现错误.
My question is, if I have a single thread, other than the EDT, that is dedicated to update a specific component, and this component is not accessed by any other thread in my program, only this dedicated thread, is it ok? In my case I have a JTable
and a thread receives information from the network and updates the table (without using EventQueue.invokeLater
). All the other components are updated from the EDT. I have not seen a problem so far, and I was wondering if a bug will surface eventually.
更新我的目的是实时更新表.数据不断地来自网络,为此,我专门为表分配了1个线程,以便在它们到来时不断对其进行更新.如果我使用SwingUtilities.invokeLater,则意味着该表将在EDT可用时进行更新.不应该将秋千用于实时更新要求吗?
UPDATEMy purpose was to update the table in real-time. The data come constantly from the network and for this I dedicated 1 thread just for the table, to update it constanlty as they come. If I use the SwingUtilities.invokeLater, this means that the table will be updated when the EDT is available. Is not swing supposed to be used for real-time update requirements?
推荐答案
有一些方法记录为线程安全的.我相信JDK7会少一些,因为事实证明其中有些是无法实现线程安全的.在大多数情况下,Swing都是线程恶意的-必须从AWT EDT线程中使用它.这主要是因为它在随机"内部使用了EventQueue.invokeLater
.还存在隐藏的共享状态(您可以更改PL& F,而不必告诉每个组件).您可以将某些类视为与线程无关的类,但未将此类文档记录下来.
There are a few methods documented as thread-safe. I believe a few less in JDK7, because it turns out some of them are unimplementable as thread-safe. For the most part Swing is thread-hostile - it has to be used from the AWT EDT thread. This is largely because it uses EventQueue.invokeLater
internally at "random". Also there is hidden shared state (you can change the PL&F without having to tell each component for instance). Some classes you may be able to treat as thread-agnostic, but they are not documented as such.
所以答案是,始终将EDT用于Swing.与大多数线程错误一样,您似乎似乎摆脱了它,然后突然在生产中失败.该错误很可能难以诊断和再现(特别是如果仅在某些系统上的生产中发生).修复严重损坏的代码库可能不会很有趣.从一开始就保持清洁.
So the answer is, always use the EDT for Swing. As with most threading bugs, you might seem to get away with it and then suddenly fail in production. The bug is likely to be difficult to diagnose and reproduce (particularly if it only happens in production on certain systems). Fixing a code base that is severely broken may not be fun. Keep it clean from the start.
这篇关于EDT的更新是绝对规则还是有例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!