Reputation: 4597
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!
Upvotes: 0
Views: 217
Reputation: 109823
1) this code wokrs and in all cases is correct
Timer timer = new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
you have to check if javax.swing.Timer#setRepeats() have true value (default value), if isn't changed, otherwise you have a code that block Event Dispatch Thread, thenafter Swing's Timer
too,
2) don't use Thread.sleep(int)
during EDT, and untill Sleep ended caused this code block for EDT,
Upvotes: 1
Reputation: 206996
Is that the complete program (is that the only code in your main
method)? If yes, then in the second case the program ends before the timer goes off, so it won't print anything, because the program is finished almost immediately.
Upvotes: 1
Reputation: 38561
Could it be that the Thread.sleep
is on the main
thread and that the reason nothing is printed in the second case is that the main
thread goes away and the program exits?
Upvotes: 1
Reputation: 81724
Presumably the code you're showing is in main()
. When main()
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.
Upvotes: 3