Java 如何在一段时间后退出while循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19727109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:44:10  来源:igfitidea点击:

How to exit a while loop after a certain time?

javaandroidwhile-loop

提问by Roland

I have a while loop and I want it to exit after some time has elapsed.

我有一个 while 循环,我希望它在经过一段时间后退出。

For example:

例如:

while(condition and 10 sec has not passed){

}

采纳答案by Ankit Rustagi

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.

检查自循环开始以来是否已经过了 10 秒或 10,000 毫秒。

EDIT

编辑

As @Julien pointed out, this may fail if your code block inside the while loop takes a lot of time.Thus using ExecutorServicewould be a good option.

正如@Julien 指出的那样,如果 while 循环中的代码块花费大量时间,这可能会失败。因此使用ExecutorService将是一个不错的选择。

First we would have to implement Runnable

首先我们必须实现 Runnable

class MyTask implements Runnable
{
    public void run() { 
        // add your code here
    }
}

Then we can use ExecutorService like this,

然后我们可以像这样使用ExecutorService,

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();

回答by Choc13

Something like:

就像是:

long start_time = System.currentTimeMillis();
long wait_time = 10000;
long end_time = start_time + wait_time;

while (System.currentTimeMillis() < end_time) {
   //..
}

Should do the trick. If you need other conditions as well then just add them to the while statement.

应该做的伎俩。如果您还需要其他条件,那么只需将它们添加到 while 语句中即可。

回答by Julien

Proposed and accepted solutions won't do the trick.

提出和接受的解决方案不会成功。

It won't stop the loop after 10 seconds. Imagine the code in your loop takes 20 seconds to process and is called at 9.9 seconds. Your code would exit after 29.9 seconds of execution.

它不会在 10 秒后停止循环。想象一下,循环中的代码需要 20 秒来处理,并在 9.9 秒时被调用。您的代码将在执行 29.9 秒后退出。

If you want to exactly stop after 10 seconds, you have to execute your code in an external thread that you will kill after a certain timeout.

如果你想在 10 秒后完全停止,你必须在一个外部线程中执行你的代码,你会在一定的超时后杀死它。

Existing solutions have already been proposed hereand there

已经在这里那里提出现有的解决方案

回答by delfer

Do not use this

不要使用这个

System.currentTimeMillis()-startTime

It may cause hang on host machine time change. Better use this way:

它可能会导致主机时间更改挂起。更好地使用这种方式:

Integer i = 0;
            try {
                while (condition && i++ < 100) {
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

(100*100 = 10 sec timeout)

(100*100 = 10 秒超时)