I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How
BalusC said:
Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().
But if you replace Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
then it doesn't compile, because the empty loop doesn't throw an InterruptedException
.
And for the thread to be interruptible, it needs to throw an InterruptedException
.
This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.
Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]