如何停止定时器线程? [英] How to stop the Timer thread?
本文介绍了如何停止定时器线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何停止定时器线程?我有一个计时器线程,我想停止它.我该怎么做?
How to stop the Timer thread? I have a timer thread and I would like to stop it. How do I do it?
我试图通过停止线程来停止,但没有成功.有任何想法吗?预先感谢您的帮助
I tried to stop by stopping the thread but it was unsuccessful. Any ideas? Thank you in advance for your help
这是我的代码:
public void startTimer() {
startTime = System.currentTimeMillis();
final Handler handler = new Handler();
task =new Thread() {
@Override
public void run() {
long millis = System.currentTimeMillis()-startTime;
long secs = millis / 1000 % 60; // seconds, 0 - 59
long mins = millis / 1000 / 60 % 60; // total seconds / 60, 0 - 59
long hours = millis / 1000 / 60 / 60; // total seconds / 3600, 0 - limitless
timeString = String.format("%02d:%02d:%02d", hours, mins, secs);
runOnUiThread(new Runnable() {
@Override
public void run() {
mtvtimer.setText(timeString);
}
});
handler.postDelayed(task, 1000);
}
};
task.start();
}
推荐答案
鉴于 Thread.stop 已弃用,您唯一的选择是添加一些您自己的信号,例如您希望它停止时设置的布尔变量.
Given that Thread.stop is deprecated, the only option you have is to add some signalling of your own, like a boolean variable that you set when you want it to stop.
例如
boolean stop = false;
public void startTimer() {
startTime = System.currentTimeMillis();
final Handler handler = new Handler();
task =new Thread() {
@Override
public void run() {
if (stop) {
return;
}
long millis = System.currentTimeMillis()-startTime;
long secs = millis / 1000 % 60; // seconds, 0 - 59
long mins = millis / 1000 / 60 % 60; // total seconds / 60, 0 - 59
long hours = millis / 1000 / 60 / 60; // total seconds / 3600, 0 - limitless
timeString = String.format("%02d:%02d:%02d", hours, mins, secs);
runOnUiThread(new Runnable() {
@Override
public void run() {
mtvtimer.setText(timeString);
}
});
handler.postDelayed(task, 1000);
}
然后从其他地方设置 stop = true
来停止它.(这是一个粗略的示例代码,只是为了让想法通过)
And from somewhere else, you set stop = true
to stop it.
(this is a rough example code, just to get the idea through)
这篇关于如何停止定时器线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文