How to exit a while loop after a certain time?

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

    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.

    EDIT

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

    First we would have to implement Runnable

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

    Then we can use ExecutorService like this,

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

提交回复
热议问题