Experimenting with the Timer, I just can not understand why main after three times outputting System.out.println("красный" + switcher); to the console System.out.println("красный" + switcher); does not end up ??? Here are 2 classes:

 public class NACHALO { public static void main(String args[]) { Timer tr1 = new Timer(); forTimerTask task = new forTimerTask(tr1); tr1.schedule(task , 0, 1000); } } 

and

 import java.util.Timer; import java.util.TimerTask; public class forTimerTask extends TimerTask{ Timer tTT = new Timer(); forTimerTask (Timer t){ tTT = t; } int switcher = 0; @Override public void run() { switcher++; System.out.println("красный" + switcher); if (switcher == 3){ tTT.cancel(); return; } } } 

    1 answer 1

    Try this:

     if (switcher == 3){ tTT.cancel(); tTT.purge(); return; } 

    cancel() will complete all logged tasks, and purge() will clear the queue, removing all completed tasks from it

    UPD: And in the forTimerTask class, the forTimerTask :

     Timer tTT = new Timer(); 

    Should be replaced by

     Timer tTT = null; 

    Because here you create a new timer, which does not allow the program to end.

    • Thank you very much! As it turned out in this case, it turned out to be decisive to replace the line Timer tTT = new Timer(); on Timer tTT = null; or just Timer tTT; But purely logically, I can’t realize it = (After all, tTT assigned tr1 to my tTT code, and then tTT , and therefore tr1 in his face, is canceled. - jack
    • It is not canceled, the object hangs in memory, but there are no references to it in your code. And the timer itself, in turn, when creating ( new Timer() ) starts a stream to which tasks will be sent, therefore, it is not collected by the garbage collector. - cache
    • PS In general, instead of the timer, I would advise using ScheduledExecutorService ru.stackoverflow.com/questions/536919/… a more advanced thing. And does not impose that your tasks inherit from TimerTask - cache