我写了一个线程,执行时间太长,而且似乎还没有完全完成。我想优雅地停止线程。有什么帮助吗?
最佳答案
最好的方法是让线程的 run()
由一个 boolean
变量保护,并在您想要停止它时从外部将其设置为 true
,例如:
class MyThread extends Thread
{
volatile boolean finished = false;
public void stopMe()
{
finished = true;
}
public void run()
{
while (!finished)
{
//do dirty work
}
}
}
从前,存在一个 stop()
方法,但正如文档所述
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.
这就是为什么你应该有一个守卫..
关于java - 如何优雅地停止java线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934255/