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.

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

关于java - 如何优雅地停止java线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194545/

相关文章:

java - 从本地机器上的多个线程通过 RMI 调用线程安全方法是否安全?

java - 自动迷宫解决方案

java - 如何找出与 unix 进程 LWP 关联的进程/任务

java - 线程安全: Instance of class

android - IntentService 或 JobScheduler 在 onPause 期间执行 I/O 密集型数据保存操作

c++ - 从主线程 c++11 执行函数调用的线程

eclipse - 我需要 JDK 才能与 Eclipse Helios 和 Tomcat 7.0.33 一起使用吗?

android - 为什么同一段(简单的)Java 代码在不同的 Android 设备上表现非常不同?

c - 多线程 - C 中矩阵乘法中偶尔出现的段错误

java - 对于现有的 Java 应用程序来说,什么是好的嵌入式语言?