title: How to interrupt a thread with infinite loop and sleep in Java
body: <p>i've been fighting with this over few hours now. Here's the code:</p>
  
  <pre><code>@Override
  public void run()
  {
      try
      {
          wscript.setBid(0.30);
  
          wscript.setServiceMode(WebScript.ServiceMode.ON);
  
          for(;!Thread.currentThread().isInterrupted();)
          {               
              Positioning(demandedPosition, maximumBid);
              if(Thread.currentThread().isInterrupted())
                  break;
              Thread.sleep(10000);
          }
          wscript.setServiceMode(ServiceMode.OFF);
          Log("Algorithm has been canceled!");
      } 
      catch (InterruptedException e)
      {
          wscript.setServiceMode(ServiceMode.OFF);
          Log("Algorithm has been canceled!");
          return;
      }
  </code></pre>
  
  <p>The thing is, that i would like to interrupt it in legit way with this code:</p>
  
  <pre><code>private void StopService()
  {
      service.interrupt();
  }
  </code></pre>
  
  <p>When I call this method when Thread.sleep() is running, it gets InterruptedException and everything works fine. However, as I call it when the PositioningAlgorithm is running nothing is happenning, the thread acts like it never got the interruption state.
  Regards,
  DualCore</p>
  
  <p>EDIT: It is essential for me that the call Log("Algorithm has been canceled!"); will be executed after interruption.</p>
  
  <p>SOLVED: I had overwritten <code>Thread.interrupt()</code> to edit class local variable which was checked whether the thread is ready to end:</p>
  
  <pre><code>service = new Thread(mechanism)
              {
                  @Override
                  public void interrupt()
                  {
                      super.interrupt();
                      mechanism.ReadyToReturn = true;
                  }
              };
  </code></pre>
  
  <p>And here's updated thread main algorithm:</p>
  
  <pre><code>@Override
  public void run()
  {
      try
      {
          wscript.setBid(0.30);
          wscript.setServiceMode(WebScript.ServiceMode.ON);
          for(;!ReadyToReturn || !Thread.currentThread().isInterrupted();)
          {               
              Positioning(demandedPosition, maximumBid);
              if(ReadyToReturn || Thread.currentThread().isInterrupted())
                  break;
              Thread.sleep(10000);
          }
          wscript.setServiceMode(ServiceMode.OFF);
          Log("Algorithm has been canceled!");
  
      } 
      catch (InterruptedException e)
      {
          wscript.setServiceMode(ServiceMode.OFF);
          Log("Algorithm has been canceled!");
          return;
      }
  
  }
  </code></pre>