2010-02-20 146 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