如何停止通过实现可运行接口创建的线程?

新手上路,请多包涵

我通过实现可运行接口创建了类,然后在我项目的其他类中创建了许多线程(近 10 个)。

如何停止其中一些线程?

原文由 svkvvenky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 332
2 个回答

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true , and may also throw an InterruptedException under certain circumstances where线程正在 _等待_,例如 Thread.sleep() , otherThread.join() , object.wait() 等。

run() 方法中,您需要捕获该异常和/或定期检查 Thread.currentThread().isInterrupted() 值并执行某些操作(例如,突破)。

Note: Although Thread.interrupted() seems the same as isInterrupted() , it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() 没有。

其他非中断方法涉及使用正在运行的线程监视的“停止”( volatile )标志。

原文由 Bohemian 发布,翻译遵循 CC BY-SA 3.0 许可协议

如何停止通过实现可运行接口创建的线程?

有许多方法可以停止线程,但所有这些方法都需要特定的代码来完成。停止线程的典型方法是设置线程经常检查的 volatile boolean shutdown 字段:

   // set this to true to stop the thread
  volatile boolean shutdown = false;
  ...
  public void run() {
      while (!shutdown) {
          // continue processing
      }
  }

您还可以中断导致 sleep()wait() 和其他一些方法抛出 InterruptedException 的线程。您还应该使用以下方法测试线程中断标志:

   public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          // continue processing
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
          }
      }
  }

请注意,使用 interrupt() 中断线程 不一定 会立即引发异常。只有当您处于可中断的方法中时,才会抛出 InterruptedException

如果您想将 shutdown() 方法添加到实现 Runnable 的类中,您应该定义自己的类,例如:

 public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

原文由 Gray 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题