我有这个模块用于应用程序 COMM 的多个部分(在 SWT Ui 端、后端等)。这个模块有一个 sendMessage 方法,我想在其中添加一个例程来确定调用线程(只是为了在 UI 中使用它)是 SWT UI 线程。并警告程序员,他正在尝试从 UI 线程执行耗时的操作……这很糟糕 :)
当然,我想通过不在 UI 模块(来自 COMM)上添加任何依赖项来做到这一点。
如何确定调用线程是否是 SWT UI 线程?
谢谢, 米尔恰
最佳答案
您可以调用 Display.getThread() 来获取应用程序的当前 UI 线程。
如果您不想依赖 SWT UI,那么您将不得不使用反射。例如:
public static boolean isUIThread()
{
Object uiThread = null;
try
{
Class displayClass = Class.forName("org.eclipse.swt.widgets.Display");
Method getDefaultMethod = displayClass.getDeclaredMethod("getDefault", new Class[] { });
Object display = getDefaultMethod.invoke(null, new Object[] { });
Method getThreadMethod = displayClass.getDeclaredMethod("getThread", new Class[] { });
uiThread = getThreadMethod.invoke(display, new Object[] { });
}
catch(Exception e)
{
log.warn("Could not determine UI thread using reflection", e);
}
return (Thread.currentThread() == uiThread);
}
关于java - Find out if the calling thread is the SWT UI thread - 确定调用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11951786/