在您的代码段有几个误区:
- 您扩展
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