Using a variable inside a timer

I am working on a program that has print time only when a function is called. I use a timer to continuously add seconds.

    Timer gameTimer = new Timer (); 

    TimerTask time =  new TimerTask() { 
       int sec = 0; 
        public void run()
        {
            sec++;
        }
    };

    gameTimer.scheduleAtFixedRate(time, 1000, 1000); 

However, I cannot use the sec variable outside of run (), so I can print it. I tried to place sec outside of TimerTask, but of course seC ++ will not work. Any help? Thank!

+4
source share
2 answers

Since only the final variables are available in the anonymous class, but with this hack below, you can achieve what you want.

final int [] result = new int[1]; // Create a final array
TimerTask time =  new TimerTask() { 
       int sec = 0; 
        public void run()
        {
            sec++;
            result[0] = sec;
        }
    };
 // Now Print whenver you want it
 System.out.println(result[0]);

This way you do not reassign the array to a new object, just changing the contents inside it

+2
source

, . https://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html

interface CustomTimerTask extends TimerTask {
    public int getTicks();
}

CustomTimerTask time =  new CustomTimerTask () { 
   int sec = 0;
    @Override 
    public void run()
    {
        sec++;
    }

    @Override
    public synchronized int getTicks() {
        return sec;
    }
};

System.out.println("The time passed is: " + time.getTicks());

, , .

+3

Source: https://habr.com/ru/post/1679775/


All Articles