如何在一段时间后退出一段时间的循环?
2022-09-02 00:08:00
我有一段时间循环,我希望它在一段时间后退出。
例如:
while(condition and 10 sec has not passed){
}
我有一段时间循环,我希望它在一段时间后退出。
例如:
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();