代码之家  ›  专栏  ›  技术社区  ›  Basti

Android isInterrupted()中断线程后返回false

  •  0
  • Basti  · 技术社区  · 7 年前

    我有一个线程等待通知或超时

      while (!isInterrupted()) {
       try {
        if (!semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
          Context context = getContext();
          // this is where i do my stuff
          semaphore.aquire();
        }
      } catch (InterruptedException ignored) {
         ignored.printStackTrace();
      }
    }
    

    在我退出应用程序之前,我会打电话给 Thread#interrupt() 在这条线上现在我调试了中断似乎执行得很好,因为 InterruptedException 被抛出,等待已被取消。
    但出于某种原因 isInterrupted() 之后仍然返回true,while循环继续运行。

    为什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   masoud vali    7 年前

    您可以在while循环条件项中使用布尔值,因为当您发送中断命令时,它不会停止线程,线程本身决定何时停止自己