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

查看:30
本文介绍了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天全站免登陆