我有一个while循环,我希望它在经过一段时间后退出.
例如:
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毫秒.
编辑
正如@Julien指出的那样,如果你在while循环中的代码块占用了大量的时间,这可能会失败.因此使用ExecutorService将是一个不错的选择.
首先,我们必须实现Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
然后我们可以像这样使用ExecutorService,
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();
标签:android,java,while-loop
来源: https://codeday.me/bug/20191001/1837745.html