如何优雅地停止一个java线程?

如何优雅地停止一个java线程?

问题描述:

我写了一个线程,执行时间太长,似乎还没有完全完成.我想优雅地停止线程.有什么帮助吗?

I wrote a thread, it is taking too much time to execute and it seems it is not completely done. I want to stop the thread gracefully. Any help ?

好的 方法是让线程的 run() 由一个boolean 变量,当你想停止它时,从外部将其设置为 true,例如:

The good way to do it is to have the run() of the Thread guarded by a boolean variable and set it to true from the outside when you want to stop it, something like:

class MyThread extends Thread
{
  volatile boolean finished = false;

  public void stopMe()
  {
    finished = true;
  }

  public void run()
  {
    while (!finished)
    {
      //do dirty work
    }
  }
}

从前存在一个 stop() 方法,但正如文档所述

Once upon a time a stop() method existed but as the documentation states

这种方法本质上是不安全的.使用 Thread.stop 停止线程会使其解锁所有已锁定的监视器(这是未经检查的 ThreadDeath 异常向上传播堆栈的自然结果).如果之前受这些监视器保护的任何对象处于不一致状态,则损坏的对象将对其他线程可见,从而可能导致任意行为.

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.

这就是为什么你应该有一个守卫..

That's why you should have a guard..