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?
Asked
Active
Viewed 348 times
1
-
1Did you consider the possibility of running that in a separate thread? – Shashank Kadne Jun 27 '20 at 06:24
-
1`I would like to move on to the next line of code if this happens` did you mean to interrupt that line if it takes too long? – Animesh Sahu Jun 27 '20 at 07:10
-
@AnimeshSahu Yes, that's what I meant. Thank you in advance! – bw01 Jun 27 '20 at 07:55
-
1Does this answer your question? [Simple timeout in java](https://stackoverflow.com/questions/19456313/simple-timeout-in-java) – Animesh Sahu Jun 28 '20 at 03:18
1 Answers
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
-
3Then 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