java.util.Timer

标签 java timer

if(e.getSource()==continuous)
{

    TimerTask task = new TimerTask()
    {
        public void run()
        {
            rollthedice();
        }
    };
    timer.schedule(task, java.util.Calendar.getInstance().getTime(), 500);


}

    if(e.getSource()==stop)
    {

        timer.cancel();

    }

我点击连续按钮,rollthedice()每秒执行循环两次,我点击停止按钮rollthedice()停止,我一直在寻找的是一种在我点击停止开始循环后再次点击连续按钮的方法再次使用 rollthedice() 方法,停止是停止 rollthedice() 的连续循环,但我希望能够再次点击连续按钮,不知道该怎么做,我一直在寻找

更新的想法:

Runnable runner = new Runnable(){
    public void run()
    {
        rollthedice();
    }
}

if(e.getSource()==continuous)
{
  future = scheduler.scheduleAtFixedRate(runner, 0, 500, TimeUnit.MILLISECONDS);
}
if(e.getSource()==stop)
{

    future .cancel();

}

最佳答案

来自 Timer.cancel() 的 javadoc :

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

这意味着需要一个新的 Timer 实例才能再次执行 rollthedice() 方法。

关于java.util.Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089630/

相关文章:

java - 不同windows操作系统的JVM

javascript - 为定时器设置回调函数

windows-phone-7 - 如何在 wp7 应用程序中设置计时器?

java - 通过传递用户 ID 列表来更新多个用户

java - 序列化对象时出现 StackOverflowError

java - 改造 1.9 以使用 jhipster oauth 响应未填充

javascript - 如何为图像设置计时器以在 javascript 或 html 中显示?

C 定时器差值返回 0ms

c# - 游戏编程及定时器数量

java - 为什么 Rust 原生库在调用函数时会随机崩溃?