在阅读了几篇关于如何终止 Java 线程的 SO 帖子后,我相当理解为什么停止是不安全以及如何处理优雅的停止。
但解决方案针对的是 UI 线程,其中重画是问题所在,而不是真正的长时间运行 - 由线程执行的阻塞进程。
链接:
How do you kill a Thread in Java? https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
我无法从解决方案或示例中理解的一个精确点是样本试图模拟的长时间运行的部分是什么。
例如:在下面的代码中,如果我将间隔设置为 INT.MAX 会怎样。
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval); // This might take forever to complete,
// and while may never be executed 2nd time.
synchronized(this) {
while (threadSuspended && blinker==thisThread)
wait();
}
} catch (InterruptedException e){
}
repaint();
}
}
public synchronized void stop() {
blinker = null;
notify();
}
我要求这个用例的原因是,我在遗留代码库中存在一个错误,该错误在线程中运行另一个可执行文件。 现在询问用户是否希望停止线程,我们需要终止该线程,并且属于该线程的可执行文件会自动被终止。
最佳答案
停止线程的方法是友好地要求它停止。这取决于线程正在运行的代码来监听并执行该请求。
具体来说,你这样做的方法是中断线程。您的代码检查中断 - 如果线程在执行之前或期间被中断,Thread.sleep
和 Object.wait
将抛出 InterruptedException
;但你发现了中断,并忽略了它,所以你不会对其采取行动。
而不是这个:
while (condition) {
try {
Thread.sleep(...);
wait();
} catch (InterruptedException e) {
}
}
将中断置于循环之外:
try {
while (condition) {
Thread.sleep(...);
wait();
}
} catch (InterruptedException e) {
}
如果被中断,则循环终止。
关于java - 如何在 Java 线程运行时中断或终止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61877306/