Kilka błędów w fragmencie kodu:
- rozszerzyć klasę
Thread
, co nie jest naprawdę dobra praktyka
- Masz
Timer
obrębie Thread
? To nie ma sensu, jako że Timer
działa na własnym Thread
.
Należy raczej (kiedy/gdzie jest to konieczne), zaimplementować Runnable
zobaczyć here na krótki przykład, jednak nie widzę potrzeby zarówno Thread
i Timer
we fragmencie dałeś.
Proszę patrz poniższy przykład pracy Timer
który będzie po prostu zwiększamy licznik o jeden za każdym razem, gdy jest wywoływany (co 3 sekundy):
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
}
}
Uzupełnienie:
Zrobiłem krótki przykład włączenia do mieszanki Thread
. Więc teraz TimerTask
będzie jedynie przyrost counter
o 1 co 3 sekundy, a Thread
wyświetli counter
s wartość spania dla 1 sekundy za każdym razem sprawdza licznik (będzie wypowiedzieć się i timer po 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
}
}
http://www.ibm.com/developerworks/java/library/j-schedule/index.html – nullpotent
Czy jesteś pewien, że tworzysz wątek 'temperatureUp' i wywołujesz' start() '? Ten kod działa dobrze dla mnie. –
Dlaczego używałbyś zarówno nici, jak i timera? Timer działa na własnym wątku –