Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my java timer stop after seemingly random number of iterations?

Tags:

java

timer

I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.

All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.

package testing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class driver {

    static int delay = 1000; //milliseconds 
    private Timer timer;
    int i = 0;
    public driver(){
        ActionListener taskPerformer = new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                  System.out.println(i);
                  i++;
              }
          };
        timer = new Timer(delay, taskPerformer);
        timer.setInitialDelay(0);
        timer.start();
    }

    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new driver();
            }
        });
    }

}
like image 374
Ryan Brady Avatar asked Feb 16 '26 10:02

Ryan Brady


1 Answers

Everything is just right in your program, but one.

Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.

So to avoid this you simply can keep main thread busy.

Here's the simplest way :

public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                driver d = new driver();
            }
        });
        for(;;); // <-- **Check this out :D**
    } 
like image 112
Himanshu Tyagi Avatar answered Feb 18 '26 23:02

Himanshu Tyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!