java timer won't work
Why won't this work?
I would like it to print every second.
Thanks.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerforme开发者_开发知识库d(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
}
Your program terminates before the timer can run even once. When the main method is terminated the program terminates and all threads will also terminate. This includes your timer thread.
Try the following:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
while (true) /* no operation */;
}
}
Probably the timer is started in a daemon thread, and immediately after starting it, the main thread finishes.
As soon as there are only daemon threads left, the JVM may/must terminate. So you need to keep the main thread alive. For testing purposes a simple Thread.sleep(10000);
should do well.
There's nothing preventing your code from exiting immediately after the call to start
. Add Thread.sleep(10000);
after timer.start();
and you'll see the message printed.
Because your program will exit soon after main thread is finished, and since timer runs on a separate thread it won't have time to execute. Adding a Thead.Sleep call before main method end would execute your code.
You are using interface libraries (java.awt
) to write console applications.
Try this:
public static void main(String[] args) throws Exception {
while(true){
Thread.sleep(1000);
System.out.println("hello");
}
}
精彩评论