How to stop execution after a certain time in Java?

后端 未结 4 1465
攒了一身酷
攒了一身酷 2020-11-28 07:01

In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.

   while(timer) {
    //run
    //terminate         


        
4条回答
  •  星月不相逢
    2020-11-28 07:20

    Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.

    With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

提交回复
热议问题