在您的代碼段有幾個誤區:
- 您擴展
Thread
類,它是不是真的好做法
- 你有
Thread
內Timer
?這沒有什麼意義,因爲Timer
自己運行Thread
。
你還是(當/如果需要),實現一個Runnable
看到here一個簡單的例子,但是我看不到在你給的片段既是Thread
和Timer
的需要。
請參閱工作Timer
的下面的例子中,這將只是一個一個地被調用時(每3秒)增加計數器:
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
}
}
附錄:
我做了一個短將Thread
合併到混合中的示例。所以,現在的TimerTask
將僅通過1每3秒遞增counter
,並且Thread
將顯示counter
價值睡眠每它檢查計數器時間(它將終止本身和counter==3
後所述定時器)1秒時:
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
//create thread to print counter value
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("Thread reading counter is: " + counter);
if (counter == 3) {
System.out.println("Counter has reached 3 now will terminate");
timer.cancel();//end the timer
break;//end this loop
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment counter
t.start();//start thread to display counter
}
}
http://www.ibm.com/developerworks/java/library/j-schedule/index。html – nullpotent 2012-07-29 06:10:06
你確定你正在創建一個'temperatureUp'線程並調用'start()'嗎?這段代碼適合我。 – 2012-07-29 06:12:10
爲什麼你會同時使用線程和計時器?定時器運行在它自己的線程上 – 2012-07-29 06:16:28