Java util.timer固定延迟不起作用? [英] Java util.timer fixed delay not working?

查看:140
本文介绍了Java util.timer固定延迟不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着看看定时器的固定延迟方法(时间表)是如何工作的,但看起来我失败了。

I tried to see how a timer's fixed delay method (schedule) works but looks like i failed.

这是我的代码:

public class Timer_Test {    
  static Timer _a_timer;
  static int num_o_proc = 0;
  static int timer_call = 0;
  static double prog_begin_time;

public static void main(String[] args) {
    prog_begin_time = System.currentTimeMillis();

    _a_timer = new Timer();

    _a_timer.schedule(new TimerTask() {
        @Override
        public void run() {
            timer_call++;
            System.out.println(timer_call + " timer start   at " + (System.currentTimeMillis() - prog_begin_time));
            process();


            System.out.println(timer_call + " timer end   at " + (System.currentTimeMillis() - prog_begin_time));
            if (timer_call >= 5) {
                System.exit(0);
            }
        }
    }, 1000, 2000);
}

public static void process() {
    num_o_proc++;
    int local_num_o_proc = num_o_proc;
    System.out.println(local_num_o_proc + " process start   at " + (System.currentTimeMillis() - prog_begin_time));

    double _a_ = 0;
    for(int x=0; x<Integer.MAX_VALUE/2; x++) {
        _a_++;
    }
    System.out.println(local_num_o_proc + " process end   at " + (System.currentTimeMillis() - prog_begin_time));
  }
}

这就是我得到的:

1个计时器从1000.0开始

1 timer start at 1000.0

1个流程从1000.0开始

1 process start at 1000.0

1流程结束于2109.0

1 process end at 2109.0

1计时器结束于2109.0

1 timer end at 2109.0

2计时器从3000.0开始

2 timer start at 3000.0

2流程从3000.0开始

2 process start at 3000.0

2流程结束于4109.0

2 process end at 4109.0

2计时器结束于4109.0

2 timer end at 4109.0

3计时器开始于5000.0

3 timer start at 5000.0

3流程从5000.0开始

3 process start at 5000.0

3流程结束于6109.0
.....

3 process end at 6109.0 .....

计时器2不应该从4109开始(而不是3000)因为第一个计时器任务在2109(2109 + 2000)结束?
我尝试使用'scheduleAtFixedRate',它给了我完全相同的结果。
我做错了吗?或者是否有一些我无法理解的概念?

Shouldn't timer 2 start at 4109 (instead of 3000) since the first timer task ended at 2109 (2109 + 2000)? I tried using 'scheduleAtFixedRate' and it gave me exact same result. Did I do something wrong? Or is there some concept I fail to understand?

推荐答案

不,这就是它的工作方式。期间是开始时间之间的时间段,而不是结束时间和下一个开始时间之间的时间段。

Nope, that's how it is intended to work. The period is the period between start times, not the period between an end time and the next start time.

基本上你用简单的英语告诉它从1开始第二个并且在那之后每两秒执行一次所以1,3,5,7等是合乎逻辑的解释。

Basically you're telling it in plain english "start at 1 second and execute every two seconds after that" so 1, 3, 5, 7, etc is the logical interpretation.

这篇关于Java util.timer固定延迟不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆