Question:
How to find if a constantly changing integer has been the same value for 3 seconds ant not disturb other actions of the program for those 3 secs.
Code:
import java.util.*; import java.text.*; public class TimerExample { static int x=0; static int timerx = x; public static void main(String[] args) { class MyTimeTask extends TimerTask { public void run() { if(timerx != x) { timerx=x; System.out.println("x changed: " + x); } System.out.println("x: " + x); } } Timer timer = new Timer(true); timer.schedule(new MyTimeTask(), 0, 3000); for (int i=0;i<10;i++){ x=i; try { Thread.sleep(8000); } catch (InterruptedException e) { } } } }
Output:
$ java TimerExample x: 0 x: 0 x: 0 x changed: 1 x: 1 x: 1 x: 1 x changed: 2 x: 2 x: 2 x changed: 3 x: 3 x: 3 x: 3 x changed: 4 x: 4 x: 4 x: 4 x changed: 5 x: 5 x: 5 x changed: 6 x: 6 x: 6 x: 6 x changed: 7 x: 7 x: 7 x: 7 x changed: 8 x: 8 x: 8 x changed: 9 x: 9 x: 9 x: 9