How to exit a while loop after a certain time?

后端 未结 4 937
灰色年华
灰色年华 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:36

    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.

提交回复
热议问题