我有點惱人的問題。現在,我有一段代碼啓動一個線程,在該線程中設置一個計時器,然後退出該線程並繼續其生命。我的意圖是讓程序在繼續執行代碼流之前等待TimerTask完成。但是,顯然,設置一個新的TimerTask不會暫停執行以等待定時器運行。Java:在繼續執行之前等待TimerTask完成
我該如何設置,以便我的代碼到達TimerTask,等待TimerTask過期,然後繼續?我甚至應該使用計時器嗎?我到處尋找解決方案,但我似乎無法找到一個解決方案。
timer = new Timer();
Thread t = new Thread(new Runnable(){
boolean isRunning = true;
public void run() {
int delay = 1000;
int period = 1000;
interval = 10;
timerPanel.setText(interval.toString());
//Scheduling the below TimerTask doesn't wait
//for the TimerTask to finish before continuing
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timerPanel.setText(setInterval().toString());
}
}, delay, period);
System.out.println("Thread done.");
}
});
t.start();
try {
t.join(); //doesn't work as I wanted
} catch (InterruptedException e) {
e.printStackTrace();
}
endTask();
在此先感謝。
編輯:對於重複任務的混淆抱歉。我需要重複這個任務,因爲它是一個倒數計時器,每秒鐘從10變爲0。函數setInterval()最終會取消定時器。下面是相關的代碼:
private final Integer setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
您是否試過[Thread.sleep](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long))? –
你已經安排了一個重複的任務,它永遠不會完成。 –
如果你有它的計劃 - 它會重複。如果你不需要重複它,並需要等待,直到它完成 - 你不需要它。只需創建一個方法並調用它 – Tala