我如何知道是否应该在 GUI 线程内进行函数调用。
if (SwingUtilities.isEventDispatchThread()) {
// ...
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// ...
}
});
}
例如
// Should I call this within GUI thread?
jTable.getModel().setValueAt(...
或者
// Should I call this within GUI thread?
jComboBox.showPopup();
据我所知,在错误的线程中进行操作可能会产生不易察觉的问题。因此,我很难验证我是否在做正确的事情。
目前,我正在做的是,如果我不确定,我只会在 GUI 线程中调用它们
不确定这是否是最好的方法,或者有可靠的方法可以确定?
最佳答案
如果您确实需要一些超通用的“尽快调用”功能,那么像这样的助手非常有用:
void invokeAsSoonAsPossible(Runnable action) {
if (SwingUtilities.isEventDispatchThread())
action.run();
else SwingUtilities.invokeLater(action);
}
// Usage:
invokeAsSoonAsPossible(new Runnable(){
@Override
public void run() {
jTable.getModel().setValueAt(...
}
});
但我的经验告诉我,构建和记录代码是一个更好的策略,这样可以更轻松地跟踪正在运行的内容。如果您的类中有一个应在 EDT 上运行的公共(public)方法,那么 JavaDoc 是一个好 friend :
/**
* Blah blah blah, describe the method's purpose.
* <p>
* <strong>Note:</strong> This method should always be
* invoked on the Swing event dispatch thread.
*/
public Pony calulateValue() {
// go ahead and touch the components any way you please
}
您还可以在仅 EDT 方法中添加断言作为一种可执行文档:
assert SwingUtilities.isEventDispatchThread();
简而言之:如果您很难跟踪自己所在的线程,那么您的代码可能非常糟糕,以至于您很难跟踪任何内容,并且您应该担心重构代码,而不是您所在的线程。
关于java - 如何确定何时应该在 GUI 线程中进行函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968686/