使用java.util.TimerTask
java.util.Timer t = new java.util.Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("This will run every 5 seconds");
}
}, 5000, 5000);
如果您使用的是GUI,则可以使用javax.swing.Timer,例如:
int delay = 5000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("This will run every 5 seconds");
}
};
new javax.swing.Timer(delay, taskPerformer).start();
Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don’t have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.