我已经了解了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;
    }
}


以及具有此类主要方法的类。现在,我已经微不足道地使用了15秒的睡眠时间来控制timerTask运行多长时间。

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类将随着数据库服务调用等变得更加复杂。

我想要做的是,在主类中,查询timerTask返回的值,以指示何时调用timer.cancel()并终止进程。现在,如果我尝试使用MyTimerTask的count属性,它将无法正常工作。所以当我尝试在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();
  }
}

10-01 15:01
查看更多