Alcuni errori nel frammento di codice:
- si estende la classe
Thread
, che non è davvero buona pratica
- Hai un
Timer
all'interno di un Thread
? Questo non ha senso dato che a Timer
viene eseguito da solo Thread
.
Si dovrebbe piuttosto (quando/se necessario), l'attuazione di una Runnable
vedere here per un breve esempio, tuttavia non vedo la necessità sia per un Thread
e Timer
nel frammento hai dato.
Si veda l'esempio seguente di una Timer
di lavoro che si limiterà a incrementare il contatore di uno ogni volta che viene chiamato (ogni 3 secondi):
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
}
}
Addendum:
ho fatto una breve esempio di incorporazione di Thread
nel mix. Così ora la TimerTask
si limiterà a incrementare counter
da 1 ogni 3 secondi, e il Thread
visualizzerà counter
s valore letto per 1 secondi ogni volta controlla contatore (che terminerà se stessa e il timer dopo 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
}
}
fonte
2012-07-29 09:03:48
http://www.ibm.com/developerworks/java/library/j-schedule/index.html – nullpotent
Sei sicuro di creare un thread 'temperatureUp' e chiama' start() '? Questo codice funziona bene per me. –
Perché dovresti usare sia una discussione che un timer? Il timer funziona sulla sua stessa thread –