检查线程是否需要EDT? [英] Check if thread is EDT is necessary?

查看:140
本文介绍了检查线程是否需要EDT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Swing实现的UI。一个组件做一些工作可能需要一些时间,所以我使用 SwingUtilities.invokeLater 。但是,我正在阅读一些旧的代码,发现这是一个 ActionListener

  if(!SwingUtilities.isEventDispatchThread()){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
// code X
}
});
} else {
//代码X
}

我认为它是有意义的,因为它从EDT分离了代码X 。然而,我发现它很容易出错,因为我使用了几次,两次我忘了 else 部分。



问题是:是否需要检查 SwingUtilities.isEventDispatchThread()?或者我可以假设我不在EDT,总是使用 invokeLater



非常感谢。

解决方案

即使你在美国东部时间下午,调用也是可以的,但是它肯定会改变事件的时间,所以你必须确保你在EDT上不依赖于代码序列。话虽如此,一个简单的方法来避免忘记其他的东西就是用一个实用的方法来打包:

  public static void invokeInDispatchThreadIfNeeded (Runnable runnable){
if(EventQueue.isDispatchThread()){
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}

这样你永远不会忘记

另外,一般来说,你的偶像重复代码x 是一个非常糟糕的主意,因为你可能会发现,你必须修复或改进这个代码,你只会在一个地方做,在另一个地方留下一个错误。


I have an UI implemented with Swing. One component does some work that may take some time, so I use SwingUtilities.invokeLater. However, I was reading some old code and found this in an ActionListener:

if (!SwingUtilities.isEventDispatchThread()) {
    SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             // code X
         }
    });
} else {
   // code X
}

I thought that it made sense since it separates code X from the EDT. However, I found it error-prone since I have used it a couple of times and both times I forgot the else part.

The question is: is the SwingUtilities.isEventDispatchThread() checking necessary? Or could I assume that I am not in the EDT and always use invokeLater?

Thanks a lot.

解决方案

Invoking later is fine even if you are on the EDT, however it certainly changes the timing of events, so you have to be sure that you were not dependent on the sequence of the code here when you were on the EDT. That being said, a simple way to avoid forgetting the else is to wrap the call in a utility method:

public static void invokeInDispatchThreadIfNeeded(Runnable runnable) {
    if (EventQueue.isDispatchThread()) {
        runnable.run();
    } else {
        SwingUtilities.invokeLater(runnable);
    }
}

That way you never forget the else.

Also, in general in your idom repeating code x is a very bad idea, as you may find later that you have to fix or improve that code and you will only do it in one place, leaving a bug in the other.

这篇关于检查线程是否需要EDT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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