long startTime = System.currentTimeMillis(); //fetch starting time
while(false||(System.currentTimeMillis()-startTime)<10000)
{
// do something
}
Thus the statement
(System.currentTimeMillis()-startTime)<10000
Checks if it has been 10 seconds or 10,000 milliseconds since the loop started.
EDIT
As @Julien pointed out, this may fail if your code block inside the while loop takes a lot of time.Thus using ExecutorService would be a good option.
First we would have to implement Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
Then we can use ExecutorService like this,
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…