If I set a timer to execute a code every 3 seconds. If the code isn't finished in 3 seconds, what will happen? The computer will terminal the code or wait for the code finish or continue the timer, and execute the code with the unfinished code concurrently.
If the computer will execute the code with the unfinished code concurrently, what happen if a variable involve in the method. For example, the first line of run may doing i--, but last line is doing i++. If it run concurrently, when the unfinished code is still running, but a new running cycle is begin, the i value is being added by a new running cycle, so when the pervious cycle run to the last line, will the i value do wrong(because the new running cycle is doing i--, before the pervious code is finished). If yes, how to avoid it?
int delay = 0; // delay for 0 sec.
int period = 3000; // repeat 3 sec.
int i = 0;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
i--;
// Task here ...
// It may take more than 3 sec to finish, what will happen?
i++;
}
}, delay, period);