Java 给定方法的执行时间,如何在每个固定的时间段调用该方法
我有密码Java 给定方法的执行时间,如何在每个固定的时间段调用该方法,java,multithreading,concurrency,Java,Multithreading,Concurrency,我有密码 for (int i = 0; i < 10000 i++) { //call every 1000ms Thread.sleep(1000); doLongTimeOperation(); } 我需要每隔固定的时间段(1000)调用此方法。也就是说,若方法在500毫秒内执行,下一次调用应该在500毫秒之后(500+500=1000)。若方法在2000毫秒内执行,则下一次调用应在0毫秒后进行。如何实施?谢谢您的问题的简单答案是测量使用System.
for (int i = 0; i < 10000 i++) {
//call every 1000ms
Thread.sleep(1000);
doLongTimeOperation();
}
我需要每隔固定的时间段(1000)调用此方法。也就是说,若方法在500毫秒内执行,下一次调用应该在500毫秒之后(500+500=1000)。若方法在2000毫秒内执行,则下一次调用应在0毫秒后进行。如何实施?谢谢您的问题的简单答案是测量使用System.currentTimeMillis()前后测量差异所用的时间。从所需的等待时间中减去该差值
long start = System.сurrentTimeMillis();
// do stuff
long duration = System.сurrentTimeMillis()-start;
Thread.sleep (1000-duration);
最好的选择是ScheduledExecutorService.scheduleWithFixedDelay方法 scheduleWithFixedDelay(可运行命令、长初始延迟、长延迟、时间单位): 有关更多详细信息,请查看此链接: ,long,long,java.util.concurrent.TimeUnit)
没有任何计算的紧张:)。注意它与scheduleAtFixedRate方法不同。希望能有帮助。我相信你真正想要的是固定费率的日程安排 创建并执行先启用的定期操作 在给定的初始延迟之后,随后在给定的时间段内; 也就是说,执行将在最初的延迟之后开始 initialDelay+period,然后initialDelay+2*period,依此类推
查看
ScheduledExecutorService
。谢谢,这就是我所需要的,固定延迟是他不想要的特定行为。
long start = System.сurrentTimeMillis();
// do stuff
long duration = System.сurrentTimeMillis()-start;
Thread.sleep (1000-duration);
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."