回调(callback)是一种常见的程序设计模式。在这种模式中,可以指定某个特定事件发生时应该采取的动作。例如,当某种资源被释放时,应该唤醒因这个资源而被挂起的任务。

  在java.swing包中有一个Timer类,可以使用它在到达给定的时间间隔发出通知。

 1 package learnspringboot.xiao;
 2 
 3 import javax.swing.Timer;
 4 import java.awt.event.ActionEvent;
 5 import java.awt.event.ActionListener;
 6 import java.util.*;
 7 
 8 /**
 9  * @author 肖政宇
10  * @date 2019-10-23 16:22
11  * 说明:
12  */
13 public class MainFunction implements ActionListener {
14 
15     /**
16      * Invoked when an action occurs.
17      *
18      * @param e - 该参数提供了事件的相关信息,例如事件的源对象。
19      */
20     @Override
21     public void actionPerformed(ActionEvent e) {
22         System.out.println(new Date());
23     }
24 
25     public static void main(String[] args) {
26         ActionListener actionListener = new MainFunction();
27         int delay = 1000;
28         Timer timer = new Timer(delay, actionListener);
29         timer.start();
30         while (true) {
31 
32         }
33     }
34 }
View Code

 

 

 

  在构建定时器时,设置一个时间间隔,并告知计时器,每一次时间间隔到达的时候需要做哪些事情。