Ответ 1
Несколько ошибок в фрагменте кода:
- Вы расширяете класс
Thread
, который не является действительно хорошей практикой. - У вас есть
Timer
внутриThread
? Это не имеет смысла, поскольку aTimer
работает сам по себеThread
.
Вы должны (когда/где необходимо) реализовать Runnable
здесь здесь для краткого примера, однако я не вижу необходимости как для 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
будет просто увеличивать counter
на 1 каждые 3 секунды, а Thread
будет отображать значение counter
в течение 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
}
}