如何正确中断Android中的线程 [英] How to properly interrupt a thread in android

查看:433
本文介绍了如何正确中断Android中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个按钮,当单击它时,我将启动一个新线程并更改按钮的文本.如果再次按下该按钮,它将开始更快地更改其文本.

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();
}

推荐答案

我认为,最好的方法是使用变量来控制它.

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

类似的东西:

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.

额外-

作为建议,我还建议您将线程设置为非Damon(setDaemon(false)),因为它会更改布局

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

另外,给线程起一个名字(setName())是一个好习惯,以便于调试.

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

这篇关于如何正确中断Android中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆