gpt4 book ai didi

java - 使用 JRE 1.6_45 杀死线程在 WindowsXP 上不起作用

转载 作者:行者123 更新时间:2023-12-01 17:16:41 28 4
gpt4 key购买 nike

我有一个线程,它应该与 SWT GUI 线程同步运行,但是如果 10 秒后没有完成,就会有一个超时来终止该线程。编辑:我需要保持与 Java 1.4 的兼容性。

主题:

private boolean isFinished;
(...)
isFinished = false;
Thread t = new Thread ("getShellsThread") {
public void run() {
try {
logger.debug("aquirerootcont SWT entered - " + Thread.currentThread().toString());
(...)
} finally {
isFinished = true;
logger.debug ("hasShells is Finished!");
}
}
}

超时代码:

    long startTime = System.currentTimeMillis();
long timeWaited;
((Display)displays.get(i)).asyncExec (t);

while(!isFinished){
timeWaited = System.currentTimeMillis() - startTime;
logger.debug("aquireRootContainer: timeWaited: " + timeWaited);
if (timeWaited > 1000) {
logger.debug(t +" Name: " + t.getName()+" took to long and will be destroyed!");
t.interrupt ();
shell = null;
break;
}
}

此代码适用于带有 JRE 1.6 和 1.7 以及 IBM JRE 的 Windows 7 和 Windows 8。然而,对于 Windows XP,虽然 IBM JRE 工作得很好,但 JRE 1.6_45 却不行。

XP 1.6_45 上的日志显示该线程不执行任何操作,10 秒后显示:

Thread[getShellsThread,10,RMI Runtime] Name: getShellsThread took to long and will be destroyed!

Windows Taskmgr 表示 rmiregistry.exe 已被终止。

为什么这段代码会终止某个特定系统上的 RMI?任何线索都会很棒!

由于需要向后兼容,不幸的是,现在用于超时线程的大多数方法都不可用。

最佳答案

您的代码中存在严重的概念错误

Thread t = new Thread ("getShellsThread") {
};
....
((Display)displays.get(i)).asyncExec (t);

Display.asyncExec method采用 Runnable 作为参数。您正在通过Thread。如果这样做,该方法将不会在其他线程上调用 Thread 对象的 run() 方法。

您的线程对象t从未真正启动,因此当您在超时代码中调用t.interrupt()时,什么也不会发生。当然,您不会中断实际运行run()方法的线程。

<小时/>

此外,我怀疑使用 Display.asyncExec 来运行可能长时间运行的任务是一个坏主意。阅读 javadoc 后,很明显 asyncExec 在 SWT 用户界面线程上运行任务以进行显示。当它运行时,UI 线程将无法处理用户的鼠标移动、击键等事件。用户界面将“卡住”。

最后,您的超时代码实际上是一个繁忙的循环,它将消耗 CPU 周期,直到超时到期。那是糟糕的设计。

<小时/>

我认为正确的解决方案是摆脱 asyncExec(t) 调用,而是调用 t.start() 来启动线程。然后替换用于实现超时的浪费的忙等待代码。相反,使用 TimerTask 实现超时类(class)。它是在 Java 3 中引入的,因此应该可以在您的旧平台上使用。

关于java - 使用 JRE 1.6_45 杀死线程在 WindowsXP 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com