How to exit a while loop after a certain time?

后端 未结 4 938
灰色年华
灰色年华 2020-12-15 21:54

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

For example:

while(condition and 10 sec has not passed){

}
4条回答
  •  一整个雨季
    2020-12-15 22:48

    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)

提交回复
热议问题