如何在一段时间后退出while循环? [英] How to exit a while loop after a certain time?
本文介绍了如何在一段时间后退出while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个while循环,我希望它在经过一段时间后退出。
I have a while loop and I want it to exit after some time has elapsed.
例如:
while(condition and 10 sec has not passed){
}
推荐答案
long startTime = System.currentTimeMillis(); //fetch starting time
while(false||(System.currentTimeMillis()-startTime)<10000)
{
// do something
}
因此声明
(System.currentTimeMillis()-startTime)<10000
检查它是否为10秒或循环开始后10,000毫秒。
Checks if it has been 10 seconds or 10,000 milliseconds since the loop started.
编辑
正如@Julien指出的那样如果你的代码块在while循环中需要花费很多时间,这可能会失败。因此使用 ExecutorService 将是一个不错的选择。
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.
首先我们必须实现Runnable
First we would have to implement Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
然后我们可以像这样使用ExecutorService,
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();
这篇关于如何在一段时间后退出while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文