我有一个类,它装饰 Swing 中的 JTextComponent。它包含的方法可以从任何线程调用,因此我必须确保与 JTextComponent 一起使用的代码将由 AWT 线程执行。
第二个要求是,调用整个方法的线程将“等待”,直到 AWT 线程完成任务。
public String getSelectedText() {
Callable c = new Callable() {
@Override
public Object call() throws Exception {
if (area.getSelectedText() == null) {
return "";
}
return area.getSelectedText();
}
};
if (Thread.currentThread().getName().contains("AWT")) {
return (String)c.call();
}
else {
FutureTask task = new FutureTask(c);
SwingUtilities.invokeLater(task);
while (!task.isDone()) {
//waiting
}
try {
return (String)task.get();
}
catch (InterruptedException | ExecutionException ex) {
return "";
}
}
}
该代码对我来说运行良好,但仍然存在一个问题。如果有人想要使用我的类,重命名 AWT 线程,那么它就会陷入死锁。
有什么方法可以明确识别 AWT 线程并避免此问题吗?
谢谢
最佳答案
您应该检查线程是否是event dispatch thread,而不是测试名称。 :
if (EventQueue.isDispatchThread()) {
// do stuff...
}
请注意,即使您使用 AWT,您也可以调用
if (SwingUtilities.isEventDispatchThread()) {
// do stuff...
}
并得到完全相同的东西。
关于java - 识别 AWT 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21918463/