java - 如何优雅地停止java线程?

标签 java multithreading

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

最佳答案

最好的方法是让线程的 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/

相关文章:

java - 在运行时确定泛型方法参数的类型

java - 如何使用破折号作为分隔符在 JSTL 中获取语言环境?

java - JBoss有一个embeddable ejb3,Embeddable EJB3有什么用?

java - 执行replaceAll后无法删除斜线

java - 多线程和图形

multithreading - 当 condition_all() 被调用时,多个线程(正在等待一个条件变量)如何获取相关的锁?

Java thread.sleep(1) sleep 时间超过 1 毫秒

c++ - 使用 Qt 在 C++ 中进行线程串口通信

c# - Thread.CurrentThread.CurrentCulture 在线程池内的线程中不工作

java - 删除超过配额情况的 cron xml,无需等待