當我在run方法中調用cancel()時,My CheckStatus(TimerTask)沒有停止。 this.cancel()也不起作用。我究竟做錯了什麼?Java TimerTask未取消
import java.util.TimerTask;
class CheckStatus extends TimerTask {
int s = 3;
public void run() {
if (s > 0)
{
System.out.println("checking status");
s--;
}
else
{
System.out.println("cancel");
cancel();
}
}
}
我的繼承人司機
import java.util.*;
class Game {
static Timer timer;
static CheckStatus status;
public static void main(String[] args) throws InterruptedException {
CheckStatus status = new CheckStatus();
timer = new Timer();
timer.scheduleAtFixedRate(status, 0, 3000);
}
}
我期待程序一旦完成Timer就結束。 – Raptrex 2011-12-16 07:22:31
@Raptrex:但是`Timer` *沒有完成 - 它仍然可用,它只是沒有安排在其中。至於JVM意識到,別的東西可能會增加另一個任務。現在你可以讓它在守護線程中運行(將`true`傳遞給`Timer`構造函數),但是當然你需要保持主線程一直存在,直到你的任務已經取消。假設這是更大程序的一部分,很難知道如何在不知道更多上下文的情況下爲您提供建議。 – 2011-12-16 07:24:03