java:在特定秒数后运行一个函数 [英] java: run a function after a specific number of seconds

查看:110
本文介绍了java:在特定秒数后运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的功能,我希望在5秒后执行。
我怎么能用Java做到这一点?

I have a specific function that I want to be executed after 5 seconds. How can i do that in Java?

我找到了javax.swing.timer,但我真的不明白如何使用它。看起来我正在寻找比这个类更简单的东西。

I found javax.swing.timer, but I can't really understand how to use it. It looks like I'm looking for something way simpler then this class provides.

请添加一个简单的用法示例。

Please add a simple usage example.

推荐答案

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

编辑:

javadoc 说:


在最后一次对Timer对象的实时引用消失并且所有未完成的任务都已完成执行之后,计时器的任务执行线程正常终止(并且受到垃圾收集)。但是,这可能会花费任意长的时间。

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

这篇关于java:在特定秒数后运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆