Rol*_*and 14 java android while-loop
我有一个while循环,我希望它在经过一段时间后退出.
例如:
while(condition and 10 sec has not passed){
}
Run Code Online (Sandbox Code Playgroud)
Ank*_*agi 28
long startTime = System.currentTimeMillis(); //fetch starting time
while(false||(System.currentTimeMillis()-startTime)<10000)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
因此声明
(System.currentTimeMillis()-startTime)<10000
Run Code Online (Sandbox Code Playgroud)
检查自循环开始以来是否为10秒或10,000毫秒.
编辑
正如@Julien所指出的,如果你在while循环中的代码块需要花费很多时间,这可能会失败.因此使用ExecutorService将是一个不错的选择.
首先,我们必须实现Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以像这样使用ExecutorService,
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)
就像是:
long start_time = System.currentTimeMillis();
long wait_time = 10000;
long end_time = start_time + wait_time;
while (System.currentTimeMillis() < end_time) {
//..
}
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩.如果您还需要其他条件,则只需将它们添加到while语句中即可.
| 归档时间: |
|
| 查看次数: |
58961 次 |
| 最近记录: |