我有一个特定的函数,我希望在5秒后执行。我如何在Java中做到这一点呢?
我找到了javax.swing.timer,但我真的不明白如何使用它。看起来我在寻找一些比这个类提供的更简单的东西。
请添加一个简单的使用示例。
发布于 2010-02-13 23:38:37
如下所示:
// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// then, when you want to schedule a task
Runnable task = ....
executor.schedule(task, 5, TimeUnit.SECONDS);
// and finally, when your program wants to exit
executor.shutdown();如果您希望池中有更多的线程,Executor上还有各种其他的工厂方法,您可以使用它们来替代。
请记住,完成后关闭executor是很重要的。当最后一个任务完成时,shutdown()方法将干净利落地关闭线程池,并将一直阻塞到这种情况发生。shutdownNow()将立即终止线程池。
发布于 2012-07-23 21:31:16
使用javax.swing.Timer的示例
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Code to be executed
}
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!此代码将只执行一次,并且在3000毫秒(3秒)内执行。
正如camickr提到的,您应该查找"How to Use Swing Timers“作为简短的介绍。
发布于 2018-02-25 06:03:03
作为@tangens答案的一种变体:如果你不能等待垃圾回收器清理你的线程,那么在run方法结束时取消计时器。
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
// close the thread
t.cancel();
}
},
5000
);https://stackoverflow.com/questions/2258066
复制相似问题