how to call a method after a time interval?
e.g if want to print a statement on screen after 2 second, what is its procedure?
System.out.println("Printing statement after every 2 seconds");
解决方案
The answer is using the javax.swing.Timer and java.util.Timer together:
private static javax.swing.Timer t;
public static void main(String[] args) {
t = null;
t = new Timer(2000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Printing statement after every 2 seconds");
//t.stop(); // if you want only one print uncomment this line
}
});
java.util.Timer tt = new java.util.Timer(false);
tt.schedule(new TimerTask() {
@Override
public void run() {
t.start();
}
}, 0);
}
Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.
Also do not mix threads in your code while you can do it without threads!
Hope this would be helpful!