java - 如何在给定执行时间的情况下每隔固定时间调用方法

标签 java multithreading concurrency

我有一个代码

for (int i = 0; i < 10000 i++) {
     //call every 1000ms
     Thread.sleep(1000);
     doLongTimeOperation();
}

长时间运行

void doLongTimeOperation(){
     //Long time op
     Thread.sleep(randomInt);
}

我需要每隔固定的时间段(1000)调用这个方法。 IE,如果方法在 500ms 内执行,则下一次调用应该在 500ms 之后(500+500=1000)。如果方法在 2000ms 内执行,则下一次调用应该在 0ms 之后。如何实现?谢谢

最佳答案

最好的选择是 ScheduledExecutorService.scheduleWithFixedDelay 方法。

scheduleWithFixedDelay(可运行命令,长初始延迟,长延迟,TimeUnit 单位):

"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."

有关更多详细信息,请查看此链接:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable ,长,长,java.util.concurrent.TimeUnit)

没有计算任何事情的紧张:)。请注意它与 ScheduleAtFixedRate 方法不同。希望对您有所帮助。

关于java - 如何在给定执行时间的情况下每隔固定时间调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600449/

相关文章:

java - java中如何将int[]转为Integer[]?

java - 致命异常 : main java. lang.RuntimeException:无法启动 Activity ComponentInfo

java - 向 UI 线程发送消息

c++ - CreateThread()//GetLastError()返回87

c++ - 线程安全内存池

java - 如何配置每 15 分钟滚动一次日志文件的 log4j 文件附加程序

Java 线程亲和性

java - 利用java线程并发执行的方法

Java Fork 加入池卡住了

java - 使用 SwingWorker 更新 GUI