学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

关于Timer的使用

关于Timer的使用

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.Timer;

public class AnotherTimerExample{
    public static void main(String[] args){
        ActionListener taskAction=new ActionListener( ){
            public void actionPerformed(ActionEvent e) {
                System.out.println("Time::" + (new Date().toLocaleString()));
                //显示当前时间
            }
        };
        new Timer(1000,taskAction).start();//Timer每一秒轮转一次
        try {
            Thread.sleep(3 * 1000);//利用线程设定程序存在时间为3秒
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.exit(0);//结束程序进程
    }
}
这样一段代码,运行的结果显示如下:
Time::2008-4-10 22:35:19
Time::2008-4-10 22:35:19
Time::2008-4-10 22:35:20
可把
                  try {
        Thread.sleep(3 * 1000);//利用线程设定程序存在时间为3秒
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.exit(0);//结束程序进程
注释掉后,就没显示了。不知是为何?请指点。
另Timer的使用有要注意的地方吗?

TOP

new Timer()是记时程序,它是每1秒到了之后调用一次函数.如果你不暂停,还没到1秒主线程就被结束了.所以new Timer()被迫停下了..这就是为什么要暂停的原因...

[ 本帖最后由 sunkaidong 于 2008-4-10 23:03 编辑 ]
学习需要安静。。海盗要重新来过。。

TOP

sunkaidong 谢谢!

TOP

发新话题