简体   繁体   English

在指定时间内运行方法/功能

[英]Running a method/function for a specified time

I'm looking for a easy way to execute a method/function for specified time in java. 我正在寻找一种在java中执行指定时间的方法/函数的简单方法。 Something that would be like this: 有点像这样:

for(3 secs){
   x();
}

The way should be easy to implement AND should have a good performance aswell. 方式应该易于实现,并且应该具有良好的性能。

long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime <= 3000){
  x();
}

+1 for Aaron's answer, with using long finishTime = System.currentTimeMillis() + 3000 instead, moving the addition / subtraction outside of the loop, leaving only the comparison for efficiency / performance. 对于Aaron的回答+1,使用long finishTime = System.currentTimeMillis() + 3000代替,在循环外移动加法/减法,只留下效率/性能的比较。

Note however, that once you enter x(), and if x() takes a while to run, the overall loop may run for longer than your desired time. 但请注意,一旦输入x(),并且x()需要一段时间才能运行,整个循环可能会运行超过所需时间。 If x() is length, you may want to add checks for the stop condition within it as well. 如果x()是长度,您可能还想在其中添加对停止条件的检查。

I'd do 我会做

long finishTime = System.currentTimeMillis()+3000;
while(System.currentTimeMillis() <= finishTime){
  x();
}

to move the arithmetic outside the loop, for efficiency/performance 为了效率/性能,将算术移出循环

void run ( Runnable task , long milliseconds ) throws Exception
{
       new Thread ( )
       {
              public void run ( ) 
              {
                     while ( true )
                     {
                              task . run ( ) ;
                     }
              }
       } . start ( ) ;
       Thread . sleep ( milliseconds ) ;
       System . exit ( 0 ) ;
}

This will work even if the task takes longer than the time alloted. 即使任务花费的时间超过分配的时间,这也会有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM