in main if the following code is used
Timer timer = new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
Thread.sleep(3000);
boo will be printed every 200 milliseconds as expected.
While
Timer timer = new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
nothing will be output!
Presumably the code you’re showing is in
main(). Whenmain()returns, the program exits before the timer thread has a chance to get going. The sleep gives the JVM enough time to create the other thread, which then allows the JVM to keep running.