Unos pocos errores en el fragmento de código:
- amplía la clase de
Thread
, que no es realmente una buena práctica
- Usted tiene una
Timer
dentro de un Thread
? Eso no tiene sentido ya que a Timer
se ejecuta solo Thread
.
Debe más bien (cuando/si es necesario), implementar un Runnable
ver here por un corto ejemplo, sin embargo, no puede ver la necesidad tanto de un Thread
y Timer
en el fragmento que le diste.
Por favor, vea el siguiente ejemplo de un Timer
de trabajo que se limitará a incrementar el contador en uno cada vez que se llama (cada 3 segundos):
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
}
}
Adición:
hice un corto ejemplo de incorporar un Thread
en la mezcla. Así que ahora la TimerTask
se limitará a incrementar counter
en 1 cada 3 segundos, y el Thread
mostrará counter
s valor de dormir durante 1 segundo cada vez que se comprueba contador (que terminará en sí y el temporizador después de 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
¿Estás seguro de que estás creando un hilo 'temperatureUp' y llamando a' start() 'en él? Este código funciona bien para mí. –
¿Por qué usaría un hilo y un temporizador? El temporizador se ejecuta en su propio hilo –