问题

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

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

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


#1 热门回答(168 赞)

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

编辑:
javadocsays:

在最后一次对Timer对象的实时引用消失并且所有未完成的任务都已完成执行之后,计时器的任务执行线程正常终止(并且变为垃圾回收)。但是,这可能需要很长时间才能发生。


#2 热门回答(42 赞)

像这样的东西:

// 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上的各种其他工厂方法。

请记住,完成后关闭执行程序非常重要。当最后一个任务完成时,shutdown()方法将干净地关闭线程池,并将阻塞直到发生这种情况.shutdownNow()将立即终止线程池。


#3 热门回答(20 赞)

使用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"作为简短的介绍。


原文链接