簡體   English   中英

在指定時間內運行方法/功能

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

我正在尋找一種在java中執行指定時間的方法/函數的簡單方法。 有點像這樣:

for(3 secs){
   x();
}

方式應該易於實現,並且應該具有良好的性能。

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

對於Aaron的回答+1,使用long finishTime = System.currentTimeMillis() + 3000代替,在循環外移動加法/減法,只留下效率/性能的比較。

但請注意,一旦輸入x(),並且x()需要一段時間才能運行,整個循環可能會運行超過所需時間。 如果x()是長度,您可能還想在其中添加對停止條件的檢查。

我會做

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

為了效率/性能,將算術移出循環

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

即使任務花費的時間超過分配的時間,這也會有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM