Java – How to properly interrupt threads in Android

How to properly interrupt threads in Android… here is a solution to the problem.

How to properly interrupt threads in Android

In my application I have a button, and when it is clicked, I start a new thread and change the text of the button. If I press the button again, it will start changing its text faster.

I want to interrupt the thread on the second button press. What is the right thing to do?

public class TestActivity extends Activity {

Button btn;
 int i = 0;

@Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     btn = (Button)findViewById(R.id.btn);
     btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           runThread();
       }
     });
 }

private void runThread() {
    new Thread() {
      public void run() {
          while (i++ < 1000) {
              try {
                  runOnUiThread(new Runnable() {

@Override
                      public void run() {
                          btn.setText("#" + i);
                      }
                  });
                  Thread.sleep(300);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
    }.start();
}

Solution

In this case, simply keep the reference to the thread and use Thread.interrupt():

private Thread runThread() {

return new Thread() {
  public void run() {
      while (i++ < 1000) {
          try {
              runOnUiThread(new Runnable() {

@Override
                  public void run() {
                      btn.setText("#" + i);
                  }
              });
              Thread.sleep(300);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
}

And then:

 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       if (myThread != null) myThread.interrupt();
       myThread = runThread();
       myThread.start();
   }
 });

Read this article for more information and options:

How to properly stop the Thread in Java?

Related Problems and Solutions