How can one variable be decremented per second in Java? I do not use Thread.sleep()
because I do not want the running thread to fall asleep, but to decrement it in execution.
How can one variable be decremented per second in Java? I do not use Thread.sleep()
because I do not want the running thread to fall asleep, but to decrement it in execution.
Without using sleep
it is not possible or at least it would not be accurate at all.
In any case, Java offers the class Timer which allows run TimerTask
TimerTasks are tasks to execute every certain time interval.
What you will need is a class that represents the task of decreasing the variable and showing it on the screen, which extends from TimerClass
import java.util.TimerTask;
import java.util.Timer;
class Counter extends TimerTask {
int seconds = 60;
public void run() {
seconds = seconds -1;
System.out.println(seconds);
}
public static void main(String [] args){
Timer timer = new Timer();
timer.schedule(new Counter(), 0, 1000);
}
}
You can also use ScheduledExecutorService
Runnable counter= new Runnable() {
public void run() {
//decrementar variable ...;
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(counter, 0, 3, TimeUnit.SECONDS);
ScheduledExecutorService allows you to manage multiple threads and in turn allows intervening if exceptions occur, both this alternative and Timer are a better approach to impelementar a thread that sleeps every 1 sec
Thread t = new Thread(){
public void run() {
while(true) {
Thread.sleep(1000);
}
}
};
t.start()
Mainly because it better reflects the intention of your code, because it is part of the java api and some of the already implemented functions that are useful; as for example Timer has the method .cancel()
which ends the timer and discards all associated TimerTasks.