java Timer定时器停止该怎么办?

如题所述

第1个回答  推荐于2019-08-06
private void closeTimer() {
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
/**
* 计时操作 改变界面的倒计时信息
*/
private void timerOperation() {
recLen = RECENT_SECOND;
mTimer = new Timer();
timerTask = new TimerTask() {

@Override
public void run() {
// TODO Auto-generated method stub
recLen--;
if (recLen >= 0) {
Message msg = new Message();
msg.what = SECOND_UPDATE;
msg.arg1 = recLen;
handler.sendMessage(msg);
}
}
};
mTimer.schedule(timerTask, PROGRESS_DELAY, PROGRESS_PERIOD);
}本回答被网友采纳
第2个回答  2018-01-03
为每个TimerTask创建不同的Timer对象,想停止某个Timer直接调用其cancel()方法 ,写个小例子
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Test{
public static void main(String args[]) throws InterruptedException {
TimerTask task1=new TimerTask(){
public void run() {
// TODO Auto-generated method stub
System.out.println("task1");
}
};
TimerTask task2=new TimerTask(){
public void run() {
// TODO Auto-generated method stub
System.out.println("task2");
}
};
Timer t1=new Timer();
Timer t2=new Timer();
t1.schedule(task1, new Date(), 1000);//每隔一秒输出
t2.schedule(task2, new Date(), 1000);//每隔一秒输出
Thread.sleep(5000);//等待5秒
t1.cancel();//停止定时器t1
Thread.sleep(5000);//等待5秒
t2.cancel();//停止定时器t2
}
}