局部内部类-打印时间
public class AlarmClock {
private int delay;
private boolean flag;
public AlarmClock(int delay, boolean flag) {
super();
this.delay = delay;
this.flag = flag;
}
public void start(){
class printer implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result =format.format(new Date());
System.out.println("当前时间:"+result);
if(flag){
Toolkit.getDefaultToolkit().beep();
}
}
}
new Timer(delay,new printer()).start();
}
}
测试:
public class Test {
public static void main(String[] args) throws IOException {
AlarmClock clock=new AlarmClock(1000, true);
clock.start();
System.in.read();
}
}