第一点:你的循环运行timer不重新新建一个Time。
用schedule(TimerTask task, long delay, long period)这个方法就行。
第二点:你要停止,首先要确定在什么样的条件满足的时候,你的time停下。如果在运行多少次后停止下来,可以在Timer中设一个变量Count,给它一个初值,每次运行减一,到0后就cancel Timer就行了。如果你要一段时间后停止,可以在另外一个线程中延迟一段时间后,cancel这个timer,这个不太准,因为另外的线程在拿到cpu主动权后才能cancel这个Timer。给你一个利用主线程延迟的例子吧:
public class Time {
private final static Timer timer = new Timer();
private final int minutes;
public Time(int minutes) {
this.minutes = minutes;
}
public void start() {
timer.schedule(new TimerTask() {
public void run() {
playSound();
// timer.cancel();
// Time eggTimer = new Time(1);
// eggTimer.start();
}
private void playSound() {
System.out.println("Your egg is ready!");
}
}, minutes * 1 * 1000, 1000);
}
public static void main(String[] args) {
Time eggTimer = new Time(1);
eggTimer.start();
try {
Thread.sleep(5000);
timer.cancel();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
当然,如果只用两个线程,也可以直接把Timer设置成后台线程,这样主线程退出时就会自动退出了。如:
public class Time {
private final Timer timer = new Timer(true);
private final int minutes;
public Time(int minutes) {
this.minutes = minutes;
}
public void start() {
timer.schedule(new TimerTask() {
public void run() {
playSound();
// timer.cancel();
// Time eggTimer = new Time(1);
// eggTimer.start();
}
private void playSound() {
System.out.println("Your egg is ready!");
}
}, minutes * 1 * 1000, 1000);
}
public static void main(String[] args) {
Time eggTimer = new Time(1);
eggTimer.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}