您的代码段中有一些错误:
- 您扩展了
Thread课程,这不是很好的做法
- 你有一个
Timer内一个Thread?这没有意义,因为 aTimer自己运行Thread。
您应该(在必要时/在必要时)在此处Runnable实现一个简短的示例,但是我看不到您提供的代码段中需要 a和a 。ThreadTimer
请参阅下面的工作示例,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
}
}
附录:
我做了一个将 aThread加入到混合中的简短示例。因此,现在TimerTask将仅counter每 3 秒增加 1,并且每次检查计数器时Thread将显示counters 值休眠 1 秒(它将自行终止,并且计时器在 之后counter==3):
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
}
}