Java 使用任务本身的数据终止定时器任务

Java terminate a timertask using data from the task itself

我了解了 Timer 和 TimerTask 在 Java 中的工作原理。我有一种情况需要生成一个任务,该任务将 运行 以固定的时间间隔定期从数据库中检索一些数据。并且需要根据取回数据的值来终止(数据本身正在被其他进程更新)

这是我到目前为止的想法。

public class MyTimerTask extends TimerTask {

    private int count = 0;
    @Override
    public void run() {
        count++;
        System.out.println(" Print a line" + new java.util.Date() + count);
    }

    public int getCount() {
        return count;
    }
}

还有一个 class 和一个像这样的 main 方法。现在我已经简单地使用了 15 秒的睡眠来控制 timerTask 运行s.

的时间。
public class ClassWithMain {
public static void main(String[] args) {
    System.out.println("Main started at " + new java.util.Date());
    MyTimerTask timerTask = new MyTimerTask();
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(timerTask, 0, 5*10*100);

    try {
        Thread.sleep(15000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Main done"+ new java.util.Date());

}

MyTimerTask class 会随着数据库服务调用等变得更加复杂。

我希望能够做的是,在主要 class 中,询问 timerTask 返回的值以指示何时调用 timer.cancel() 并终止进程。现在,如果我尝试使用 MyTimerTask 的计数 属性,它不起作用。所以当我尝试在 ClassWithMain

中添加这些行时
if (timerTask.getCount() == 5){
    timer.cancel();
}

它没有停止进程。

所以我想知道如何才能完成我想做的事情。

private volatile int count = 0;最好用'volatile'.
在 ClassWithMain 中试试这个:

for(;;) {
  if (timerTask.getCount() == 5) {
    timer.cancel();
    break;
  } else{
    Thread.yield();
  }
}