假设我有一个看起来像这样的类:
import javax.swing.*;
import java.util.*;
public class MyClass extends JFrame
{
private java.util.Timer timer = new java.util.Timer();
...
private class MyTimerTask extends TimerTask
{
@Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000);
}
else
{
timer.schedule(new MyTimerTask(), 500);
}
}
}
}
现在,我一直想起
TimerTask
的run方法,有点像循环。它运行一次,然后,如果要再次运行,可以通过调用schedule
来运行。所以我的问题是:当我调用timer.schedule()
时,它是否会执行TimerTask
中的其他任何代码,还是像在循环中使用break
那样起作用?如果我改写这样的方法: @Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000); // method wouldn't end after this call
}
timer.schedule(new MyTimerTask(), 500);
}
它会起作用吗?
最佳答案
安排计时器任务只是方法调用;它不会导致计时器任务的run()方法的当前执行结束,因此不行,两个代码示例的功能不同。最好使用两个代码示例中的第一个,在run方法中仅调度一次任务。
关于java - 调度java.util.timer是否退出该计时器的timerTask方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22571623/