如何在Android中停止此线程?

时间:2016-12-23 12:20:32

标签: android multithreading

在Android中使用线程学习时,我创建了简单的线程,每秒更新时间textview:

Thread t = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(time!=0){
                                if(time>9){timeLeftTV.setText("0:"+time);}
                                else{timeLeftTV.setText("0:0"+time);}
                                time--;
                            }
                            else {
                                //timeLeftTV.setText("finished");
                            }
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };
    t.start();

我想在时间到期时显示对话框。如何停止此线程?

4 个答案:

答案 0 :(得分:1)

使用CountDownTimer

new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }
}.start();

这是1秒钟时间间隔的30秒示例。

您可以在onFinish()方法上显示对话框。

答案 1 :(得分:1)

我大部分时间使用的Runnable可以使用Handler进行安排,如下所示:

final int timeInterval = 1000;
final Handler handler = new Handler();
Runnable runnable = new Runnable() {

  @Override
  public void run () {

    textView.setText("time..");

    // schedule the same Runnable after one second
    handler.postDelayed(this, timeInterval); 
  }
};
handler.postDelayed(runnable, timeInterval);

要停止循环,请从Runnable

中删除Handler
handler.removeCallbacks(runnable);

当您不想使用上述方法时,只需使用Boolean即可阻止循环继续,Thread将自行结束:

boolean stop = false;
Thread t = new Thread() {

  @Override
  public void run () {

    while (!stop) {
      // do stuff
    }
  }
};
t.start();

停止Thread

stop = true;

答案 2 :(得分:0)

只需中断线程,你想要阻止它。

thread.interrupt();

答案 3 :(得分:0)

有许多方法可以阻止线程。 就像你可以使用Executor Services而不是计时器。但是对于快速解决方案,您可以继续使用以下方法:

long startTimer = System.currentTimeMillis(); long stopTimer = startTimer + 60 * 1000; // 60秒* 1000毫秒/秒

while (System.currentTimeMillis() < stopTimer)
{
    // Perform your all the required operation here
}

希望它会对你有所帮助。

对于Executor服务,请检查以下堆栈链接:

How to timeout a thread

相关问题