1

I have a line of code that might take too long to run(sometimes it does, sometimes it doesn't), and I would like to move on to the next line of code if this happens. Is there any way in Java that I can do this?

bw01
  • 39
  • 5

1 Answers1

0

You can record the start time mills,and you say it might take too long to run. So I just consider it as a loop. If so,you just need to get the end time miils , check the difference between the start time mills and the end time miils, if it is too large, just call break.

XuanXu
  • 16
  • 2
  • `I just consider it as a loop` This is not necessarily true as OP wrote `code that might take too long to run(sometimes it does, sometimes it doesn't)` probably he isn't talking about loops. – Animesh Sahu Jun 27 '20 at 07:06
  • 3
    Then just put it into a thread, wait while the thread is alive,if it takes too long, break and do other tasks. You can also keep the thread running. – XuanXu Jun 27 '20 at 07:15
  • @XuanXu Thank you, could you provide example code of how to kill a thread if it takes too long? – bw01 Jun 27 '20 at 08:21
  • It is unsafe to kill the thread if it is still running. But you can call thread.interrupt(), if the thread is in blocked state, it will throw an interrupt exception and exit. And if you don't mind, you can call stop () function to destroy it. – XuanXu Jun 27 '20 at 08:54