How to properly interrupt a thread in android

android, java, multithreading

Solution

In my opinion, the best way would be using a variable to control this.

Something like:

while(i++ < 1000 && keepRunning)

I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.

extra--

As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes

Also it is a good practice to give thread a name (setName()) to make it easy on debugging.

Problem

In my application I have a button and when it gets clicked I start a new thread and change the text of button. If I press the button again it will start changing its text faster. I would like to interrupt the thread when the button is pressed in the second time. What's the correct way to do it? ``` 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(); } ```

Original source

Related problems