2010-02-20 284 views
3

我一直在搜索Java時間戳,計時器以及任何與時間和Java有關的事情。 我似乎無法得到任何東西爲我工作。時間戳,計時器,時間問題

我需要一個時間戳來控制,如僞代碼while循環低於

while(true) 
{ 

    while(mytimer.millsecounds < amountOftimeIwantLoopToRunFor) 
    { 
     dostuff(); 
    } 

    mytimer.rest(); 

} 

任何想法,我可以使用的數據類型;我試過時間戳,但似乎沒有工作。

感謝 夏蘭

回答

2

做這樣的事情:

long maxduration = 10000; // 10 seconds. 
long endtime = System.currentTimeMillis() + maxduration; 

while (System.currentTimeMillis() < endtime) { 
    // ... 
} 

的(更先進的)方法是使用java.util.concurrent.ExecutorService。這裏有一個SSCCE

package com.stackoverflow.q2303206; 

import java.util.Arrays; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.TimeUnit; 

public class Test { 

    public static void main(String... args) throws Exception { 
     ExecutorService executor = Executors.newSingleThreadExecutor(); 
     executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.SECONDS); // Get 10 seconds time. 
     executor.shutdown(); 
    } 

} 

class Task implements Callable<String> { 
    public String call() throws Exception { 
     while (true) { 
      // ... 
     } 
     return null; 
    } 
} 
+0

非常感謝,完美的作品 – 2010-02-20 19:01:17