title: Interrupting active Thread Android
body: <p>I'm trying to make <strong>2 Threads</strong>.</p>
  
  <p>Each Thread can interrupt the other one, <strong>the two can't be running at the same time</strong>.</p>
  
  <p>I've tried to use the function Thread.interrupt(), but this not trigger an exception inside the Thread.</p>
  
  <p><em>how can I stop a running Thread at any moment? I only found solutions that involve sleeping threads or myths that Thread.Interrupt() trigger an exception, not only a flag.</em></p>
  
  <pre><code>val toTransparent: Thread = (object : java.lang.Thread() {
      override fun run() {
          try {
              if (toOpaque.isAlive)
                  toOpaque.interrupt()
              while (opacity &gt; 0) {
                  sleep(1)
                  activityForUI.runOnUiThread() {
                      searchBarEmpresa_linearLayout.background.alpha = opacity
                  }
                  opacity--
              }
          } catch (e: InterruptedException) {
              Thread.currentThread().interrupt()
              return
          }
      }
  })
  
  val toOpaque: Thread = (object : Thread() {
      override fun run() {
          try {
              if (toTransparent.isAlive)
                  toTransparent.interrupt()
              while (opacity &lt; 255) {
                  sleep(1)
                  activityForUI.runOnUiThread() {
                      searchBarEmpresa_linearLayout.background.alpha = opacity
                  }
                  opacity++
              }
          } catch (e: InterruptedException) {
              Thread.currentThread().interrupt()
              return
          }
      }
  })
  </code></pre>