我如何在Android中停止线程

时间:2016-08-27 20:56:18

标签: java android multithreading thread-safety

我试图制作一个倒计时器,用户点击一个按钮就停止了倒计时。

我在互联网上搜索了一种方法来停止控制倒计时的线程。

我尝试使用interruptInterruptedstop,但未能成功使用这些方法停止线程。

问题: 如何停止控制倒数计数器的线程?

public class Main2Activity extends AppCompatActivity {

    TextView mTextField;
    Button stop;
    Activity myActivity;
    PrimeThread T1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        myActivity=this;
        mTextField = (TextView) findViewById(R.id.counter);
        T1=new PrimeThread();
        T1.start(); }

    public void stop(View view){   T1.interrupt();    }

    class PrimeThread extends Thread {
        int i=10;
        public void run() {
            while(i>0){
                myActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextField.setText("00:0"+i);
                    }
                });
                i--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }}}
}

1 个答案:

答案 0 :(得分:2)

你可以在你的线程中放置一个标志:

public class Main2Activity extends AppCompatActivity {

    TextView mTextField;
    Button stop;
    Activity myActivity;
    PrimeThread T1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        myActivity=this;
        mTextField = (TextView) findViewById(R.id.counter);
        T1=new PrimeThread();
        T1.start(); }

    public void stop(View view){   T1.stopRunning();    }

    class PrimeThread extends Thread {
        int i=10;
        boolean running = false;
        public void run() {
            running = true;
            while(running && i < 10){
                i++;
                myActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextField.setText("00:0"+i);
                    }
                });
                i--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void stopRunning(){
            running = false;
        }
    }
}