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/